To understand what's going on here, compare what happens in a similar example, where I want to set any numbers bigger than 20 to -1:
numbers = [1, 10, 30, 40, 50]
for number in numbers:
if number > 20:
number = -1
print(numbers) # same as before!
Why does this not set the last three numbers to -1? Because number
here is a value—it's location in memory is totally unrelated to the contents of the numbers
array. word
in your example is exactly the same.
Inside your loop, word
is bound to a new piece of memory whose contents happen to be the same as the current entry of the words
array. By the time word
is defined in your first snippet, you have lost any way to manipulate the array location it came from. By iterating over the indexes like in your second snippet, you keep a back door into the array.
These two references,
might help understand the following tricky business: instead of a list of strings, what happens if we have a list of lists?
listOfLists = [[1], [2, 3], [9, 10, 11], [40, 50, 60, 70]]
for l in listOfLists:
if len(l) >= 3:
l[:] = l[::-1] # note that `[:]`!!!
print(listOfLists)
This actually will reverse any sub-list that has more than 2 elements. Can you understand why? If so, take this gold star: !