问题
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 list_reversed[i]=list[len(list)-1-i] and print(list[i]) (commenting the last line of course) leads to a change in list. What am I not seeing? My Python version is 3.3.3. Thank you in advance.
list=[1,2,3,4,5,6]
list_reversed=list
for i in range(0,len(list)):
#list_reversed[i]=list[len(list)-1-i]
#print(list[i])
print(list[len(list)-1-i])
回答1:
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.
回答2:
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!!
回答3:
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.
回答4:
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.
回答5:
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[:]
来源:https://stackoverflow.com/questions/21537078/unexpected-list-behavior-in-python