Search code examples
python-3.xlistsyntaxargument-unpacking

Concept of unpacking a list in Python-- conflicting rules of syntax


>>> x = [1,3]
>>> x
[1, 3]
>>> x[0]
1
>>> x[1]
3
>>> x,y = [1,3]
>>> x
1
>>> y
3
>>> x[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable

As I understand it, a list is a value in and of itself. As such, it can be assigned to a variable.

This is evident in the above code, where x = [1,3] and x returns the list value of [1,3]. However, if there are two variables to the left of the assignment operator, things change. The list to the right of the variable is no longer the value, but, instead, the elements of the list are the values.

Would someone be kind enough to explain why this is so. Thanks in advance.

Perhaps I've misunderstood what "unpacking" is. Do the rules change when there are multiple variables to the left of the assignment operator?


Solution

  • This is a simple assignment:

    x = [1, 3]
    

    This is unpacking:

    x, y = [1, 3]
    

    Maybe this is what you want:

    x = y = [1, 3]
    x[0] # 1
    

    Explanation

    Observe that x, y is actually convenience for (x, y):

    (x, y) = [1, 3]
    
    x = 1, 3
    x # (1, 3)
    

    That's why having multiple values on the left behaves differently.