Unexpected list behavior in Python

前端 未结 5 537
-上瘾入骨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: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.

提交回复
热议问题