Questions tagged [iterable-unpacking]

A Python feature in which elements of an iterable are simultaneously assigned to multiple variables, e.g. a, b, c = [1, 2, 3].

Iterable unpacking (sometimes known as 'tuple unpacking', although the concept applies equally to any iterable, not just tuples) is a feature of Python which allows for the assignment of the elements of an iterable to be assigned to multiple variables:

>>> a, b, c = [1, 2, 3]
>>> a
1
>>> b
2
>>> c
3

This feature can be used to swap the values of two variables without the use of a temporary 'holding' variable, as traditionally employed in other languages:

>>> a = 1
>>> b = 2
>>> a, b = b, a
>>> a
2
>>> b
1
>>> # rather than:
... a = 1
>>> b = 2
>>> temp = a
>>> a = b
>>> b = temp
>>> a
2
>>> b
1

If the number of elements in the iterable does not match the number of variables on the left hand side of the assignment, A ValueError is raised:

>>> d, e = 4, 5, 6
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
>>> f, g, h = 7, 8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack

Since Python 3, Extended iterable unpacking allows "spare" elements of the iterable to be assigned to a list (note the *):

>>> x, *y, z = "kapow"
>>> x
'k'
>>> y
['a', 'p', 'o']
>>> z
'w'
469 questions
-3
votes
1 answer

How to group the same values into same key?

I have an assignment to do this things without import any helpful function, could you guys help me? Thanks! data = [ ['num','e1','e2','e3'], ['2002','p','r','i'], ['2002','k','r','i'], ['2001','k','r','e'], ['2004','p','a','p'], …
-3
votes
2 answers

While Loop failing to Unpack Iterable

I'm working with a function that has many different options (contained in "if" and "elif" statements) which all increment or decrement 4 different variables. Once the function ends, I need to unpack the resulting values back to the original…
Austin
  • 1
-4
votes
4 answers

How to unpack a nested list in Python3?

Lst = [[1,2,3],[201,202,203],[3,1,4],[591,2019,3.14]] What I need is- a1,b1,c1 = (1,2,3) a2,b2,c2 = (201,202,203) and so on ...
user9916003
  • 15
  • 1
  • 1
-4
votes
2 answers

I don't get how tuple unpacking works (Python-2.x)

as I was wondering how tuple unpacking was working, I've found on several threads this answer as an alternative to slicing : >>>>def unpack(first,*rest): return first, rest which works as…
Raphael_LK
  • 199
  • 2
  • 13
1 2 3
31
32