I have an iterator over a mutable sequence, e.g.
foo = [1, 2, 3, 4, 5]
for bar in foo:
Is there a way to write to the elements in foo by using the reference which is contained in the iterator? The naive assignment:
bar = 42
does not work of course. Is it possible to use the "behind the curtain" reference to the sequence element which is in the iterator ?
PS: The simple solution with using an index
for i in range(len(a)):
a[i] = 42
will not work for my case, as I can't expose the container name.
for
loop requires a reference, so to get back to the original container all you need is that same reference.bar
is one such reference, the list referenced byfoo
is another. Which one is the 'true' reference you wanted to rebind here? What if I copied thefoo
list into another, should references to42
be rebound in that list too?