Code_Jeena
Code_Jeena

Reputation: 1

for loop does not run till the end index of the list

Below code runs for two times only. No idea why it is happening.

a=[1,2,3,4]
count=0
for letter in a:
    print(letter)
    b=a.pop()

    count+=1
print("total loop count is "+str(count))

I expect that the loop should run for four times. If I comment / remove line b=a.pop(), then the loop runs for four times.

I expect print for the count after the program exit loop should be four, but actual output print for the count is 2.

Upvotes: 0

Views: 313

Answers (5)

Manjunath Rao
Manjunath Rao

Reputation: 4260

Just to understand the concept. Use enumerate() to know the count of the iteration, When the pop is called for the second time the len(a) becomes 2(which means there is no 3rd item to print for the third iteration). run below code once to get a better idea. It is sot recommended to pop or remove from the list inside for loop.

count=0
for iteration_count,letter in enumerate(a):
    print("Index Value:",iteration_count)
    b=a.pop()
    print("Length of a:",len(a))
    count+=1
print("total loop count is "+str(count))

While the below code would help you if you want to pop all the items.

count=0
while a:
    a.pop()
    print(a)

Upvotes: 0

Joe Zhow
Joe Zhow

Reputation: 1009

Because you change the element size of the iterator a using the line:

b=a.pop()

every time running the line, the list a will remove its last element and the size of it will be reduced by 1.

the simplest way to get your expection is to make the iterator unchangeable at line 3 for letter in a[:]:

a=[1,2,3,4]
count=0
for letter in a[:]:
    print(letter)
    b=a.pop()

    count+=1
print("total loop count is "+str(count))

and the output will be correct:

1
2
3
4
total loop count is 4

Upvotes: 0

sahasrara62
sahasrara62

Reputation: 11228

a little improved code

a=[1,2,3,4]
count=0
while len(a)>0:
    count+=1
    print(a[-1])
    a.pop()

print("total loop count is {}".format(count))

Upvotes: 0

Ire
Ire

Reputation: 1361

The list.pop() method without a parameter removes the last item of the list. Check out the documentation.

So basically what happens is:

  • Loop 1 (letter is 1, 4 is removed)
  • Loop 2 (letter is 2, 3 is removed)
  • No loop 3 since the list a has no more elements.

Generally it is considered bad practice to modify a collection when iterating on its elements. Doing so often results in unintended behavior.

Upvotes: 7

yonutix
yonutix

Reputation: 2439

1st step: print the first element, remove the 4th one

2nd step: print the second element, removes the 3rd one

... no elements left to print.

Upvotes: 2

Related Questions