0

This is driving me crazy. I'm iterating a list in python and if something is empty, I want to change its value. Why this simple thing is not working?

>>> list = ['WHY', 'this', 'isnt', '', 'working']
>>> for item in list:
...     if item == '':
...             item = 'Nevermind'
...
>>>
>>> print list
['WHY', 'this', 'isnt', '', 'working']
Ry-
  • 218,210
  • 55
  • 464
  • 476
Jack
  • 722
  • 3
  • 8
  • 24
  • When you iterate on the list, you get a copy of the values in the list, so if you modify it, you modify your copy, not the value in the list. If you want to modify the list, you have to work with an index, like `for i in range(len(list)): if list[i] == "": list[i] = "Nevermind" – Thomas Kowalski May 16 '17 at 18:32
  • 1
    @ThomasKowalski Although your solution is correct, your diagnoses is wrong. You *do not get a copy of the values*, The same values are assigned to the iterator variable, and no copies are made, because *assignment never copies in python*. The problem is that in the code above, you assign something else to the iterator variable, but of course, this assignment doesn't affect your list, because assignment never mutates an object. [Required reading](https://nedbatchelder.com/text/names.html) – juanpa.arrivillaga May 16 '17 at 18:34

0 Answers0