How assignment works with Python list slice?

前端 未结 4 1201
灰色年华
灰色年华 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:24

    When you specify a on the left side of the = operator, you are using Python's normal assignment, which changes the name a in the current context to point to the new value. This does not change the previous value to which a was pointing.

    By specifying a[0:2] on the left side of the = operator, you are telling Python you want to use Slice Assignment. Slice Assignment is a special syntax for lists, where you can insert, delete, or replace contents from a list:

    Insertion:

    >>> a = [1, 2, 3]
    >>> a[0:0] = [-3, -2, -1, 0]
    >>> a
    [-3, -2, -1, 0, 1, 2, 3]
    

    Deletion:

    >>> a
    [-3, -2, -1, 0, 1, 2, 3]
    >>> a[2:4] = []
    >>> a
    [-3, -2, 1, 2, 3]
    

    Replacement:

    >>> a
    [-3, -2, 1, 2, 3]
    >>> a[:] = [1, 2, 3]
    >>> a
    [1, 2, 3]
    

    Note:

    The length of the slice may be different from the length of the assigned sequence, thus changing the length of the target sequence, if the target sequence allows it. - source

    Slice Assignment provides similar function to Tuple Unpacking. For example, a[0:1] = [4, 5] is equivalent to:

    # Tuple Unpacking
    a[0], a[1] = [4, 5]
    

    With Tuple Unpacking, you can modify non-sequential lists:

    >>> a
    [4, 5, 3]
    >>> a[-1], a[0] = [7, 3]
    >>> a
    [3, 5, 7]
    

    However, tuple unpacking is limited to replacement, as you cannot insert or remove elements.

    Before and after all these operations, a is the same exact list. Python simply provides nice syntactic sugar to modify a list in-place.

提交回复
热议问题