Understanding *x ,= lst

前端 未结 4 1504
礼貌的吻别
礼貌的吻别 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 12:56

    *x ,= p is basically an obfuscated version of x = list(p) using extended iterable unpacking. The comma after x is required to make the assignment target a tuple (it could also be a list though).

    *x, = p is different from x = p because the former creates a copy of p (i.e. a new list) while the latter creates a reference to the original list. To illustrate:

    >>> p = [1, 2]
    >>> *x, = p 
    >>> x == p
    True
    >>> x is p
    False
    >>> x = p
    >>> x == p
    True
    >>> x is p
    True
    

提交回复
热议问题