I have a list of numbers t. I want to multiply the numbers in the list with 10. Why does this not work?:
for i in t
i = i*10
Why do I have to do this?:
for i in range(len(t)):
t[i] = t[i]*10
I have a list of numbers t. I want to multiply the numbers in the list with 10. Why does this not work?:
for i in t
i = i*10
Why do I have to do this?:
for i in range(len(t)):
t[i] = t[i]*10
Well, it doesn't work because that's no the correct syntax. You could, however, clean things up a bit with a list comprehension:
t = [x * 10 for x in t]
It doesn't work that way in Python.
The index variable (your i
) of the for .. in
construct is just a variable. At the start of each pass through the loop, Python assigns the corresponding value from the in
sequence to the loop's index variable. It's as if you had a lot of copies of the loop body, and before each copy you put an assignment statement i = t[0]
, i = t[1]
, and so on. The index variable does not remember that it was assigned from the in
sequence (your t
). The index variable is not an equivalent name (an "alias") for the corresponding value of the in
sequence. Changing the index variable does not affect the in
sequence.
python -c 't = [1, 2, 3]
for i in t:
i = 1
print t'
[1, 2, 3]
But you're not wrong to wonder whether it's an alias! Another language that is frequently compared with Python does work that way (quoting manual page "perlsyn"):
If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop. Conversely, if any element of LIST is NOT an lvalue, any attempt to modify that element will fail. In other words, the foreach loop index variable is an implicit alias for each item in the list that you're looping over.
So:
perl -e '@t = (1, 2, 3); foreach $i (@t) { $i = 1; } print @t'
111