Understanding *x ,= lst

前端 未结 4 1502
礼貌的吻别
礼貌的吻别 2021-01-30 12:22

I\'m going through some old code trying to understand what it does, and I came across this odd statement:

*x ,= p

p is a list in t

4条回答
  •  走了就别回头了
    2021-01-30 13:08

    It's a feature that was introduced in Python 3.0 (PEP 3132). In Python 2, you could do something like this:

    >>> p = [1, 2, 3]
    >>> q, r, s = p
    >>> q
    1
    >>> r
    2
    >>> s
    3
    

    Python 3 extended this so that one variable could hold multiple values:

    >>> p = [1, 2, 3]
    >>> q, *r = p
    >>> q
    1
    >>> r
    [2, 3]
    

    This, therefore, is what is being used here. Instead of two variables to hold three values, however, it is just one variable that takes each value in the list. This is different from x = p because x = p just means that x is another name for p. In this case, however, it is a new list that just happens to have the same values in it. (You may be interested in "Least Astonishment" and the Mutable Default Argument)

    Two other common ways of producing this effect are:

    >>> x = list(p)
    

    and

    >>> x = p[:]
    

    Since Python 3.3, the list object actually has a method intended for copying:

    x = p.copy()
    

    The slice is actually a very similar concept. As nneonneo pointed out, however, that works only with objects such as lists and tuples that support slices. The method you mention, however, works with any iterable: dictionaries, sets, generators, etc.

提交回复
热议问题