2

In Python it is not possible to modify a list while iterating over it. For example, below I cannot modify list_1 and the result of the print will be [0, 1, 2, 3, 4]. In the second case, I loop over a list of class instances, and calling the set_n method modifies the instances in the list, while iterating over it. Indeed, the print will give [4, 4, 4, 4, 4].

How are these two cases different, and why?

# First case: modify list of integers 
list_1 = [0, 1, 2, 3, 4]
for l in list_1:
    l += 1
print(list_1)

# Second case: modify list of class instances
class Foo:
    def __init__(self, n):
        self.n = n
        
    def set_n(self, n):
        self.n = n
        
list_2 = [Foo(3)] * 5
for l in list_2:
    l.set_n(4)
print([l.n for l in list_2])
1
  • 1
    This is not a duplicate of the other questions; the question isn't about whether it's safe to modify the elements, and it isn't about why it isn't safe to add or remove elements. The question is why assigning to the iteration variable doesn't modify the corresponding element in the underlying list. We need a proper canonical for that. Leaving this closed for now, but. Commented Sep 23, 2022 at 17:18

1 Answer 1

7

It certainly is possible to modify a list while iterating over it, you just have to reference the list, not a variable that contains the list value.

for i in range(len(list_1)):
    list_1[i] += 1

The difference in the second case is that the variable contains a reference to a mutable container object. You're modifying the contents of that object, not assigning to the variable.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.