I have a for loop as follows:
a=[1,2,3,4,5]
for i in a:
i=6
What I would like is for every element of a to become 6.
Now I know that this for loop won’t do it, because I am merely changing the what i refers to.
I instead could write:
a=[1,2,3,4,5]
for i in len(range(a)):
a[i]=6
But that doesn’t seem very Pythonic. What are good ways of doing this sort of thing? Obviously, setting everything to 6 is contrived example and, in reality, I would be doing more complicated (and wonderful) things. Therefore, answers should be generalised.
The
for-variable is always a simple value, not a reference; there is no way to know that it came from a list and thus write back to the list on changing.The
len(a)approach is the usual idiom, although you needrange(orxrange) too:or, just as commonly, use the
enumeratefunction to get indexes as well as values:a list comprehension might be a good alternative, eg: