When I have a for loop:
for row in list:
row = something_or_other
It seems that sometimes I can assign a value (or append/extend etc.) directly to row and the list changes accordingly, and sometimes I have to do something roundabout like:
for row in list:
list[list.index(row)] = something_or_other
What gives?!?
You can never reassign the value
row(or in general, whatever your iterating variable is) like this:because this is reassigning the variable
xentirely (it’s saying “forget thatxwas a member of a list”).However, if
xis mutable, for example if it’s a list, you can do:and it will actually change the values (to
[[1, 2, 10], [3, 4, 10]]). In technical terms, this is the difference between a rebinding and mutating operations.