Understanding *x ,= lst

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 this context. I've been trying to figure out what this statement does. As far as I can tell, it just sets x to the value of p. For example:

    p = [1,2]
    *x ,= p    
    print(x)

Just gives

    [1, 2]

So is this any different than x = p? Any idea what this syntax is doing?

*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

From: stackoverflow.com/q/43190992

Back to homepage or read more recommendations: