Updating a sliced list

后端 未结 4 1502
野性不改
野性不改 2021-02-19 04:12

I thought I understood Python slicing operations, but when I tried to update a sliced list, I got confused:

>>> foo = [1, 2, 3, 4]
>>> foo[:1]          


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-19 05:07

    Use

    foo[1]  = 'two'
    

    and

    foo[2:] = ['three', 'four']
    

    and it works.

    The answer why is in the comment above (because you're using a copy)

提交回复
热议问题