I've written a seemingly simple loop. There are 6 items in the list and it should loop six times. However, it only loops 3 times. Why?
list1 = 'one two three four five six'
newlist = list1.split(' ')
print (newlist)
list2 = ['seven', 'eight', 'nine', 'ten', 'eleven', 'twelve']
for number in list2:
nextnumber = list2.pop()
print ("Adding number ", nextnumber)
newlist.append(nextnumber)
print (newlist)
As mentioned in the comments, you remove items while iterating. You can model this pattern better with a while loop:
while list2:
newlist.append(list2.pop())
Adding list2 to newlist using a for loop could be done like this:
for number in list2:
print ("Adding number ", number)
newlist.append(number)
But the short, fast and pythonic way is
newlist.extend(list2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With