The reason that variable == new_word
is always true is that the assignment operator in this case merely creates a new pointer, not a new list.
In other words, variable = new_word
does not make a copy of the list -- it makes variable
point to the same list in memory. So when you reverse variable
, you are actually reversing the original list. You can see this if you print new_word
after you have run variable.reverse()
.
This article is a helpful introduction to pointers, and this one is a nice explanation of assignment vs. shallow-copy vs. deep-copy. Since your list is just a list of strings, shallow-copy will do the trick.[1] Deep-copy is overkill, but it works too.
Shallow-copy:
variable = list(new_word)
For Python 3.3 and later, lists have a built-in copy
method:
variable = new_word.copy()
Another option is to use slicing, but without supplying a starting or ending index:
variable = new_word[:]
Finally, the copy
module supplies a function for creating shallow copies:
variable = copy.copy(new_word)
Deep-copy:
import copy
variable = copy.deepcopy(new_word)
[1] While mrtnlrsn says you have made a shallow copy, this is not true, as the linked articles explains.