I wanted to reverse a list, and I managed to do so, but in the middle of the work I noticed something strange. The following program works as expected but uncommeting line <
The following:
list_reversed = list
makes the two variables refer to the same list. When you change one, they both change.
To make a copy, use
list_reversed = list[:]
Better still, use the builtin function instead of writing your own:
list_reversed = reversed(list)
P.S. I'd recommend against using list
as a variable name, since it shadows the builtin.
This is about general behaviour of lists in python. Doing:
list_reversed = list
doesn't copy the list, but a reference to it. You can run:
print(id(list_reversed))
print(id(list))
Both would output the same, meaning they are the same object. You can copy lists by:
a = [1,2]
b = a.copy()
or
a = [1,2]
b = a[:]
list
and reversed_list
are the same list. Therefore, changing one also changes the other.
What you should do is this:
reversed_list = list[::-1]
This reverses and copies the list in one fell swoop.
list_reversed = list
does not make a copy of list. It just makes list_reversed
a new name pointing to the same list. You can see any number of other questions about this on this site, some list in the related questions to the right.
When you do:
list_reversed = list
You don't create a copy of list
, instead, you create a new name (variable) which references the same list you had before. You can see this by adding:
print(id(list_reversed), id(list)) # Notice, the same value!!