Setting list values
Published: Wednesday, Dec 26, 2007 Last modified: Thursday, Nov 14, 2024
How to set a list value in a for loop.
>>> list = range(5)
>>> list
[0, 1, 2, 3, 4]
>>> for i in list:
... i = i + 1
...
>>> list
[0, 1, 2, 3, 4]
We desired [1, 2, 3, 4, 5] A list comprehension:
>>> [i + 1 for i in list]
[1, 2, 3, 4, 5]