0

I am confused about a really simple problem with list built-in function, pop.

The code is simple as it can be.

L=[1,2]
for i in L:
    print i
    L.pop(0)

and it gives

1

I tried it with a longer list

L=[1,2,3,4,5,6]
for i in L:
    print i
    L.pop(0)

and it gave me

1
3
5

So, back to the first code, what I thought was from the line 'for i in L', the for loop will run for '1' first, so it will print i and then L.pop(0) will remove '1' from L. Then, there will be another loop for '2 in L', which will print 2, making L empty list. However, it only returned 1, and 1,3,5 in case of second case. What am I missing here?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
Jimmy Suh
  • 202
  • 2
  • 13

2 Answers2

3

What am I missing here?

You are missing some basic concepts of for loop here.

You are popping from the start of the list by using pop(0). So after popping, all elements shift one position left and hence changing the indexes of every remaining element. In this case for loop's next() method yields newly shifted element for the current index it holds. Hence you see such behaviour.

If you change your code by adding some print statement, it will become more clear.

L=[1,2,3,4,5,6]
for i in L:
    print L, i
    L.pop(0)

# Output
[1, 2, 3, 4, 5, 6] 1 # It has index 0 here
[2, 3, 4, 5, 6] 3 # It has index 1 here
[3, 4, 5, 6] 5 # It has index 2 here
# 6 is not printed here  as it has index 3 to print here but our L is reduced to [4, 5, 6] which does not contain any index 3
Amit Yadav
  • 1,861
  • 2
  • 20
  • 27
0
L=[1,2]
for i in L:
   print i
   L.pop(0)

In this example you will get output as 1 because foreach loop runs only one time. In the first iteration where i=0, L[i] equals to 1 and print it. When you pop down one item from the list length of the list is to be 1. So foreach loop will automatically break after L.pop(0) statement

L=[1,2,3,4,5,6]
for i in L:
   print i
   L.pop(0)

In this code, consider the first iteration where i=0. It will print the 1. Then by pop the first element from the list length of the list will be 5. Now list is auto adjust as [2,3,4,5,6]. By considering next iteration when i is equal to 1, it will print 3 where L[1]=3. After that popping the first element of list causing L=[3,4,5,6]. Finally print 5 as L[2].