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
60
votes
11 answers

How to extract dictionary single key-value pair in variables

I have only a single key-value pair in a dictionary. I want to assign key to one variable and it's value to another variable. I have tried with below ways but I am getting error for same. >>> d = {"a": 1} >>> d.items() [('a', 1)] >>> (k, v) =…
user966588
55
votes
2 answers

Unpacking tuples in a python list comprehension (cannot use the *-operator)

I am trying to create a list based on another list, with the same values repeated 3 times consecutively. At the moment, I am using: >>> my_list = [ 1, 2 ] >>> three_times = [] >>> for i in range( len( my_list ) ): ... for j in range( 3 ): ... …
DRz
  • 1,078
  • 1
  • 11
  • 29
55
votes
3 answers

Unpacking argument lists for ellipsis in R

I am confused by the use of the ellipsis (...) in some functions, i.e. how to pass an object containing the arguments as a single argument. In Python it is called "unpacking argument lists", e.g. >>> range(3, 6) # normal call with…
mhermans
  • 2,097
  • 4
  • 18
  • 31
52
votes
3 answers

SyntaxError with starred expression when unpacking a tuple on its own for string formatting

I tried the following using the REPL in Python 3.5.2: >>> a = (1, 2) >>> '%d %d %d' % (0, *a) '0 1 2' >>> '%d %d %d' % (*a, 3) '1 2 3' >>> '%d %d' % (*a) File "", line 1 SyntaxError: can't use starred expression here >>> My question,…
gboffi
  • 22,939
  • 8
  • 54
  • 85
46
votes
4 answers

Meaning of using commas and underscores with Python assignment operator?

Reading through Peter Norvig's Solving Every Sudoku Puzzle essay, I've encountered a few Python idioms that I've never seen before. I'm aware that a function can return a tuple/list of values, in which case you can assign multiple variables to the…
matt b
  • 138,234
  • 66
  • 282
  • 345
45
votes
1 answer

Python: Unpacking an inner nested tuple/list while still getting its index number

I am familiar with using enumerate(): >>> seq_flat = ('A', 'B', 'C') >>> for num, entry in enumerate(seq_flat): print num, entry 0 A 1 B 2 C I want to be able to do the same for a nested list: >>> seq_nested = (('A', 'Apple'), ('B',…
Kit
  • 30,365
  • 39
  • 105
  • 149
43
votes
2 answers

Is it possible to return two lists from a function in python

I am new to python programming and need your help for the following: I want to return two lists from a function in python. How can i do that. And how to read them in the main program. Examples and illustrations would be very helpful. Thanks in…
heretolearn
  • 6,387
  • 4
  • 30
  • 53
41
votes
2 answers

Unpacking generalizations

PEP 448 -- Additional Unpacking Generalizations allowed: >>> LOL = [[1, 2], ['three']] >>> [*LOL[0], *LOL[1]] [1, 2, 'three'] Alright! Goodbye itertools.chain. Never liked you much anyway. >>> [*L for L in LOL] File…
wim
  • 338,267
  • 99
  • 616
  • 750
40
votes
1 answer

How does swapping of members in tuples (a,b)=(b,a) work internally?

In [55]: a = 5 In [56]: b = 6 In [57]: (a, b) = (b, a) In [58]: a Out[58]: 6 In [59]: b Out[59]: 5 How does this swapping of values of a and b work internally? Its definitely not using a temp variable.
praveen
  • 3,193
  • 2
  • 26
  • 30
39
votes
4 answers

Is it possible to unpack a tuple in Python without creating unwanted variables?

Is there a way to write the following function so that my IDE doesn't complain that column is an unused variable? def get_selected_index(self): (path, column) = self._tree_view.get_cursor() return path[0] In this case I don't care about…
Nathan
  • 5,272
  • 2
  • 26
  • 28
39
votes
7 answers

How do I convert a tuple of tuples to a one-dimensional list using list comprehension?

I have a tuple of tuples - for example: tupleOfTuples = ((1, 2), (3, 4), (5,)) I want to convert this into a flat, one-dimensional list of all the elements in order: [1, 2, 3, 4, 5] I've been trying to accomplish this with list comprehension. But…
froadie
  • 79,995
  • 75
  • 166
  • 235
37
votes
5 answers

unpacking an array of arguments in php

Python provides the "*" operator for unpacking a list of tuples and giving them to a function as arguments, like so: args = [3, 6] range(*args) # call with arguments unpacked from a list This is equivalent to: range(3, 6) Does anyone…
sgibbons
  • 3,620
  • 11
  • 36
  • 31
35
votes
4 answers

Python update object from dictionary

Is there a built-in function/operator I could use to unpack values from a dictionary and assign it into instance variables? This is what I intend to do: c = MyClass() c.foo = 123 c.bar = 123 # c.foo == 123 and c.bar == 123 d = {'bar':…
chakrit
  • 61,017
  • 25
  • 133
  • 162
35
votes
3 answers

Python star unpacking for version 2.7

As mentioned here, you can use the star for unpacking an unknown number of variables (like in functions), but only in python 3: >>> a, *b = (1, 2, 3) >>> b [2, 3] >>> a, *b = (1,) >>> b [] In python 2.7, the best I can come up with is (not…
beardc
  • 20,283
  • 17
  • 76
  • 94
1
2
3
31 32