Unexpected list behavior in Python

前端 未结 5 531
-上瘾入骨i
-上瘾入骨i 2020-12-04 03:23

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 <

相关标签:
5条回答
  • 2020-12-04 03:37

    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.

    0 讨论(0)
  • 2020-12-04 03:45

    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[:]
    
    0 讨论(0)
  • 2020-12-04 03:46

    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.

    0 讨论(0)
  • 2020-12-04 03:52

    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.

    0 讨论(0)
  • 2020-12-04 03:54

    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!!
    
    0 讨论(0)
提交回复
热议问题