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

前端 未结 7 935
灰色年华
灰色年华 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 19:52

    a[2:4] is a copy of the list a that is built using the 2,3,4 items in list a. The first two work because you are assigning the changes into those spots in the original list. The last one doesn't work because you are not affecting the original list.

提交回复
热议问题