3

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)
martineau
  • 119,623
  • 25
  • 170
  • 301
Erich Purpur
  • 1,337
  • 3
  • 14
  • 34

6 Answers6

1

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())
user2390182
  • 72,016
  • 6
  • 67
  • 89
1

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)
Jesper
  • 1,611
  • 13
  • 10
1

Use the following code instead:

for number in list2:
    print ("Adding number ", number)
    newlist.append(number)
print (newlist)

Observation: The list2.pop() is reducing your list element and it also reduces the number looping times

0

It only only loops out three times because you are actively modifying list2. A simple correction would be to make a copy!!

import copy

list2_c = copy.copy(list2)

for num in list2_c:
.
.
.
.
0

Quick answer, make a copy of list2:

list1 = 'one two three four five six'
newlist = list1.split(' ')
print (newlist)
list2 = ['seven', 'eight', 'nine', 'ten', 'eleven', 'twelve']

for number in list(list2):
    nextnumber = list2.pop()
    print ("Adding number ", nextnumber)
    newlist.append(nextnumber)

print (newlist)
thachnb
  • 1,503
  • 10
  • 13
0

like the previous answers are saying, you are tempering with list2, in other word when you do for number in list2, you are taking 7, 8,9 but never using them, but instead you are removing 12, 11, 10 from the list and printing it. you could do it this way instead:

    for number in list2:
    #Unless you want to append in reverse order(see below for that)
    #comment the next line
        #nextnumber = list2.pop() 
        print ("Adding number ", number) 
        newlist.append(number)#Append the number you just got from list2
    print (newlist)

  out[:]: ['one', 'two', 'three', 'four', 'five', 'six']
  Adding number  seven
  Adding number  eight
  Adding number  nine
  Adding number  ten
  Adding number  eleven
  Adding number  twelve
  ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 
  'ten', 'eleven', 'twelve']

If you want to append in reverse order, do what @thachnb suggested.

LeStivi
  • 31
  • 5