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
786
votes
4 answers

What do ** (double star/asterisk) and * (star/asterisk) mean in a function call?

In code like zip(*x) or f(**k), what do the * and ** respectively mean? How does Python implement that behaviour, and what are the performance implications? See also: Expanding tuples into arguments. Please use that one to close questions where OP…
288
votes
10 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
  • 87,323
  • 22
  • 191
  • 272
134
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
  • 43,129
  • 22
  • 67
  • 91
122
votes
2 answers

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
  • 1,726
  • 2
  • 15
  • 24
118
votes
3 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
  • 14,809
  • 13
  • 61
  • 106
96
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,918
  • 7
  • 33
  • 50
89
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
  • 14,679
  • 16
  • 53
  • 68
86
votes
1 answer

Why is starred iterable unpacking in a return statement invalid syntax without parentheses before Python 3.8?

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
  • 12,125
  • 9
  • 63
  • 94
86
votes
8 answers

How are tuples unpacked in for loops?

I stumbled across the following code: for i, a in enumerate(attributes): labels.append(Label(root, text = a, justify = LEFT).grid(sticky = W)) e = Entry(root) e.grid(column=1, row=i) entries.append(e) entries[i].insert(INSERT,"text to…
Talisin
  • 2,370
  • 3
  • 18
  • 17
80
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
  • 3,327
  • 5
  • 26
  • 45
78
votes
4 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,4) a = myTuple[0] b = myTuple[2] Or something like (a,_,b,_) = myTuple Is there a way I could unpack the values, but…
Jim Jeffries
  • 9,841
  • 15
  • 62
  • 103
75
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,489
  • 21
  • 77
  • 126
75
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
  • 47,306
  • 11
  • 48
  • 68
66
votes
1 answer

What does *tuple and **dict mean in Python?

As mentioned in PythonCookbook, * can be added before a tuple. What does * mean here? Chapter 1.18. Mapping Names to Sequence Elements: from collections import namedtuple Stock = namedtuple('Stock', ['name', 'shares', 'price']) s = Stock(*rec) #…
heLomaN
  • 1,634
  • 2
  • 22
  • 33
63
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,112
  • 1
  • 9
  • 17
1
2 3
31 32