Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop only loops 3 times. Why? [duplicate]

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)
like image 699
Erich Purpur Avatar asked Dec 19 '25 07:12

Erich Purpur


2 Answers

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())
like image 117
user2390182 Avatar answered Dec 21 '25 20:12

user2390182


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)
like image 24
Jesper Avatar answered Dec 21 '25 20:12

Jesper