Home > database >  Modifying the list inside for loop in python
Modifying the list inside for loop in python

Time:09-07

Could looping over a list using the for loop and using the pop and append method inside cause any issues? Is there an alternate safe way? I know in Java it causes problems, and so you use iterators either explicitly or implicitly. Is there something similar in Python?

My Thoughts:
It does cause issues, I tried this program:

l=[1,2]
for elem in l:
     l.pop(0)
     l.append(1)
     print(elem)  

The output was 1,1,2,1. Now I am removing an element and appending an element. So after the first iteration, l will become [2]->[2,1] (pop and append), then it becomes [1]->[1,1] not sure how it produces the current output and stops. It does cause some issues. Is there any logic behind this?

CodePudding user response:

I would create a duplicate list and keeping it unchanged to loop into it:

l = [1, 2]
t = list(l) # note that I use the list function  
# not to use the same allocation in memory for both of the list.  
# If I didn't, the operations you do to a list will be done also to the other one.
for elem in t:
    l.pop(0)
    l.append(1)
    print(elem)
print(l, t)

printed output:

1
2
[1, 1] [1, 2]

CodePudding user response:

The loop has an implicit counter, so yes, any modifications to the list's length will cause unexpected issues.

However, since you add and append the same number of elements, then your output should actually be 1 1 ...

# cat app.py
l=[1,2]
for elem in l:
     l.pop(0)
     l.append(1)
     print(elem)
# python3 /tmp/app.py
1
1


To override the elements of the list in a loop, you'd use position assignment like so

l = [1,2]
for i, elem in enumerate(l):
     print(f'before: {elem}')
     elem = 1  # not necessary, and only sets the variable within the current loop iteration
     l[i] = elem
     print(f'after: {elem}')
  • Related