How assignment works with Python list slice?

前端 未结 4 1202
灰色年华
灰色年华 2020-11-21 23:19

Python doc says that slicing a list returns a new list.
Now if a "new" list is being returned I\'ve the following questions related to "Assignment to sl

4条回答
  •  我寻月下人不归
    2020-11-21 23:34

    I came across the same question before and it's related to the language specification. According to assignment-statements,

    1. If the left side of assignment is subscription, Python will call __setitem__ on that object. a[i] = x is equivalent to a.__setitem__(i, x).

    2. If the left side of assignment is slice, Python will also call __setitem__, but with different arguments: a[1:4]=[1,2,3] is equivalent to a.__setitem__(slice(1,4,None), [1,2,3])

    That's why list slice on the left side of '=' behaves differently.

提交回复
热议问题