Unexpected list behavior in Python

前端 未结 5 539
-上瘾入骨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: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[:]
    

提交回复
热议问题