How do I reverse a part (slice) of a list in Python?

前端 未结 7 911
灰色年华
灰色年华 2020-11-27 19:32

Why doesn\'t this work?

# to reverse a part of the string in place 
a = [1,2,3,4,5]
a[2:4] = reversed(a[2:4])  # This works!
a[2:4] = [0,0]             # Thi         


        
7条回答
  •  情歌与酒
    2020-11-27 20:12

    a[2:4] creates a copy of the selected sublist, and this copy is reversed by a[2:4].reverse(). This does not change the original list. Slicing Python lists always creates copies -- you can use

    b = a[:]
    

    to copy the whole list.

提交回复
热议问题