質問

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])
役に立ちましたか?

解決

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.

他のヒント

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!!

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.

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.

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[:]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top