Modify a list while iterating

Viewed 35543

I know you should not add/remove items while iterating over a list. But can I modify an item in a list I'm iterating over if I do not change the list length?

class Car(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return type(self).__name__ + "_" + self.name

my_cars = [Car("Ferrari"), Car("Mercedes"), Car("BMW")]
print(my_cars)  # [Car_Ferrari, Car_Mercedes, Car_BMW]
for car in my_cars:
    car.name = "Moskvich"
print(my_cars)  # [Car_Moskvich, Car_Moskvich, Car_Moskvich]

Or should I iterate over the list indices instead? Like that:

for car_id in range(len(my_cars)):
    my_cars[car_id].name = "Moskvich"

The question is: are the both ways above allowed or only the second one is error-free?

If the answer is yes, will the following snippet be valid?

lovely_numbers = [[41, 32, 17], [26, 55]]
for numbers_pair in lovely_numbers:
    numbers_pair.pop()
print(lovely_numbers)  # [[41, 32], [26]]

UPD. I'd like to see the python documentation where it says "these operations are allowed" rather than someone's assumptions.

4 Answers

Examples where the list is modified and not during while iterating over the elements of the list

list_modified_during_iteration.py

a = [1,2]
i = 0
for item in a:
      if i<5:
          print 'append'
          a.append(i+2)
      print a
      i += 1

list_not_modified_during_iteration.py (Changed item to i)

a = [1,2]
i = 0
for i in range(len(a)):
    if i<5:
        print 'append'
        a.append(i+2)
    print a
    i += 1
Related