How to modify list elements while iterating over the list?

Question:

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])
Asked By: G. Gare

||

Answers:

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.

Answered By: Barmar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.