In-place modification of Python lists

I found this in the docs: https://docs.python.org/3/tutorial/controlflow.html#for

Python’s for statement iterates over the items of any sequence (a list
or a string), in the order that they appear in the sequence.

If you need to modify the sequence you are iterating over while inside
the loop (for example to duplicate selected items), it is recommended
that you first make a copy. Iterating over a sequence does not
implicitly make a copy.

I was wrong in my first response, when iterating through a list it returns the actual items in that list. However, it seems they cannot be edited directly while they are being iterated through. This is why iterating through the integers the length of the list works.

As for why the .reverse() function works, I think it’s because it is affecting a list instead of a value. I tried to use similar built in functions on nonlist datatypes like .replace() on strings and it had no effect.

All of the other list functions I tried worked: .append(), .remove(), and .reverse() as you showed. I’m not sure why this is, but I hope it clears up what you can do in for loops a bit more.

Answer to old question below:

The way you are using the for loops doesn’t affect the actual list, just the temporary variable that is iterating through the list. There are a few ways you can fix this. Instead of iterating through each element you can can count up to the length of the list and modify the list directly.

c = [1,2,3]
for n in range(len(c)):
    c[n] += 3
print(c) 

You can also use the enumerate() function to iterate through both a counter and list items.

c = [1,2,3]
for n, x in enumerate(c):
    c[n] = x + 3
print(c) 

In this case, n is a counter and x is the item in the list.

Finally, you can use list comprehension to generate a new list with desired differences in one line.

c = [1, 2, 3]
d = [x + 3 for x in c]
print(d)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)