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'
404 questions
660
votes
5 answers

What does the star and doublestar operator mean in a function call?

What does the * operator mean in Python, such as in code like zip(*x) or f(**k)? How is it handled internally in the interpreter? Does it affect performance at all? Is it fast or slow? When is it useful and when is it not? Should it be used in a…
264
votes
8 answers

"unpacking" a tuple to call a matching function pointer

I'm trying to store in a std::tuple a varying number of values, which will later be used as arguments for a call to a function pointer which matches the stored types. I've created a simplified example showing the problem I'm struggling to…
Flexo
  • 82,006
  • 22
  • 174
  • 256
230
votes
12 answers

How can I convert a dictionary into a list of tuples?

If I have a dictionary like: { 'a': 1, 'b': 2, 'c': 3 } How can I convert it to this? [ ('a', 1), ('b', 2), ('c', 3) ] And how can I convert it to this? [ (1, 'a'), (2, 'b'), (3, 'c') ]
mike
  • 40,704
  • 43
  • 97
  • 111
113
votes
4 answers

Unpacking, extended unpacking and nested extended unpacking

Consider the following expressions. Note that some expressions are repeated to present the "context". (this is a long list) a, b = 1, 2 # simple sequence assignment a, b = ['green', 'blue'] # list asqignment a, b…
treecoder
  • 36,160
  • 18
  • 57
  • 89
88
votes
2 answers

Getting only element from a single-element list in Python?

When a Python list is known to always contain a single item, is there a way to access it other than: mylist[0] You may ask, 'Why would you want to?'. Curiosity alone. There seems to be an alternative way to do everything in Python.
Pyderman
  • 10,029
  • 9
  • 46
  • 85
83
votes
6 answers

Tuple Unpacking in Map Operations

I frequently find myself working with Lists, Seqs, and Iterators of Tuples and would like to do something like the following, val arrayOfTuples = List((1, "Two"), (3, "Four")) arrayOfTuples.map { (e1: Int, e2: String) => e1.toString + e2 } However,…
duckworthd
  • 13,061
  • 13
  • 48
  • 67
80
votes
1 answer

Python tuple unpacking in return statement

The Python language (especially 3.x) allows very general unpacking of iterables, a simple example of which is a, *rest = 1, 2, 3 Over the years, this unpacking has been gradually generalized (see e.g. PEP 3132 and PEP 448), allowing it to be used…
jmd_dk
  • 8,399
  • 4
  • 48
  • 72
73
votes
8 answers

Why is Scala's syntax for tuples so unusual?

In mathematics and computer science, a tuple is an ordered list of elements. In set theory, an (ordered) n-tuple is a sequence (or ordered list) of n elements, where n is a positive integer. So, for example, in Python the 2nd item of a tuple would…
yura
  • 14,149
  • 19
  • 71
  • 123
73
votes
4 answers

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…
Kewl
  • 2,817
  • 3
  • 20
  • 42
64
votes
7 answers

pandas apply function that returns multiple values to rows in pandas dataframe

I have a dataframe with a timeindex and 3 columns containing the coordinates of a 3D vector: x y z ts 2014-05-15 10:38 0.120117 0.987305 0.116211 2014-05-15 10:39 0.117188 …
Fra
  • 4,068
  • 5
  • 27
  • 46
63
votes
5 answers

Django - How to do tuple unpacking in a template 'for' loop

In my views.py, I'm building a list of two-tuples, where the second item in the tuple is another list, like this: [ Product_Type_1, [ product_1, product_2 ], Product_Type_2, [ product_3, product_4 ]] In plain old Python, I could iteration the…
Chris Lawlor
  • 41,304
  • 11
  • 45
  • 67
61
votes
5 answers

Why can a dictionary be unpacked as a tuple?

Today, I saw one statement which didn't throw an exception. Can anyone explain the theory behind it? >>> x, y = {'a': 2, 'b': 5} >>> x 'a' >>> y 'b'
nik_kgp
  • 1,092
  • 1
  • 9
  • 17
57
votes
2 answers

Ignore part of a python tuple

If I have a tuple such as (1,2,3,4) and I want to assign 1 and 3 to variables a and b I could obviously say myTuple = (1,2,3) a = my_tuple[0] b = myTuple[2] Or something like (a,_,b,_) = myTuple Is there a way I could unpack the values, but ignore…
Jim Jeffries
  • 9,051
  • 13
  • 57
  • 99
50
votes
1 answer

Type hints when unpacking a tuple?

Is it possible to use type hinting when unpacking a tuple? I want to do this, but it results in a SyntaxError: from typing import Tuple t: Tuple[int, int] = (1, 2) a: int, b: int = t # ^ SyntaxError: invalid syntax
Cai
  • 850
  • 9
  • 20
1
2 3
26 27