In fact with list comprehension you are not modifying the list, you are creating a new list and then assigning it to the variable that contained the previous one.
Anyway, when you do for i in li
you are getting a copy of each value of li
in variable i
, you don't get the reference to a position in li
, so you are not modifying any value in li
.
If you want to modify your list you can do it with enumerate
:
>>> li = ["spam", "eggs"]
>>> for i,_ in enumerate(li):
li[i] = "foo"
>>> li
['foo', 'foo']
or with xrange
(in Python 2.7, use range in python 3):
>>> for i in xrange(len(li)):
li[i] = "foo"
>>> li
['foo', 'foo']
or with the list comprehension you showed in your question.