Change value of currently iterated element in list

for a in _list_:
  _list_[_list_.index(a)]=123

Because python iterators are just a "label" to a object in memory, setting it will make it just point to something else.

If the iterator is a mutable object (list, set, dict etc) you can modify it and see the result in the same object.

>>> a = [[1,2,3], [4,5,6]]
>>> for i in a:
...    i.append(10)
>>> a
[[1, 2, 3, 10], [4, 5, 6, 10]]

If you want to set each value to, say, 123 you can either use the list index and access it or use a list comprehension:

>>> a = [1,2,3,4,5]
>>> a = [123 for i in a]
>>> a
[123, 123, 123, 123, 123]

But you'll be creating another list and binding it to the same name.


for idx, a in enumerate(foo):
    foo[idx] = a + 42

Note though, that if you're doing this, you probably should look into list comprehensions (or map), unless you really want to mutate in place (just don't insert or remove items from iterated-on list).

The same loop written as a list comprehension looks like:

foo = [a + 42 for a in foo]

Tags:

Python