[Tutor] tuple unpacking

Martin A. Brown martin at linux-ip.net
Sat Nov 21 11:28:48 EST 2020


Hi Manprit,

> According to me these are all examples of tuple unpacking because variables
> written on the left side of the assignment statement in above given
> examples -     a, b, c are nothing but a tuple, and we are unpacking the
> values of iterable on the right side to  it
> 
> is my understanding correct ?

I would say yes.

> 
> I just need to know the definition of tuple unpacking.  need to know if the
> examples that i am writing below belongs to tuple unpacking or not :
> 
> Example 1 :
> >>> a, b, c = (2, 3, 6)
> >>> a
> 2
> >>> b
> 3
> >>> c
> 6
> >>>

Let's try breaking your example in the interpreter.

>>> a, b, c = (2, 3, 6)
>>> a, b, c = (2, 3, 6, 7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 3)

I see the word unpack.


> Example 2:
> >>> x, y, z = [3, 6, 5]
> >>> x
> 3
> >>> y
> 6
> >>> z
> 5
> >>>

>>> x, y, z = [3, 6, 5, 7]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 3)

Example 2 is identical except that the right-hand side is a list, 
but yes, it's still an iterable.

> Example 3:
> >>> a, b, c, d = (i for i in range(1, 8) if i%2 != 0)
> >>> a
> 1
> >>> b
> 3
> >>> c
> 5
> >>> d
> 7
> >>>

>>> a, b, c, d = (i for i in range(1, 7) if i%2 != 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 4, got 3)

Same deal, just a generator on the right hand side.

> Similarly values in set and dicts keys can be assigned to 
> variables written on the left side of the assignment statement , 
> provided the number of variables on the left of the assignment 
> statement must be equal to the iterable on right side .

And, one thing I do not do often enough is to take advantage of 
this:

>>> f0, f1, *rest = fibonacci
>>> f0
0
>>> f1
1
>>> rest
[1, 2, 3, 5, 8]

This allows you to grab a predictable number of elements in your 
unpacking and store the remainder for further processing later in 
the program.

Nice usage of the interprter to demonstrate your question.

-Martin

-- 
Martin A. Brown
http://linux-ip.net/


More information about the Tutor mailing list