for loop not iterating through all list elements in python

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



for loop not iterating through all list elements in python


things="pen pencil apple mango litchi grapes pear song music"
stuff=things.split(" ")
items=["a","b","c","d"]

for word in items:
next_one=items.pop()
stuff.append(next_one)
print(stuff)



when I run this code, the resulting list shows that only last two elements are appended from items. Why is it not appending all the elements?





stuff.append(word) remove next_one=items.pop()
– Rakesh
Aug 7 at 10:17


stuff.append(word)


next_one=items.pop()




1 Answer
1



Therefore that you modify items reference You will only add two elements.
Below you can see all values in items variable in every step of loop.



STEP 1



items = ["a","b","c","d"]
next_one = 'd'



STEP 2



items = ["a","b","c"]
next_one = 'c'



STEP 3



items = ["a","b"]
So here the loop ends



To solve it you can change


for word in items:



to


while(items):



Or you can write it in one line:


stuff.extend(list(reversed(items)))





Why does the loop ends when items list has only "a" and "b" ?
– Rasleen
Aug 8 at 19:39





Here you will find the answer quora.com/…
– Rafał
Aug 8 at 19:55






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard