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
32
votes
3 answers

Python: Splat/unpack operator * in python cannot be used in an expression?

Does anybody know the reasoning as to why the unary (*) operator cannot be used in an expression involving iterators/lists/tuples? Why is it only limited to function unpacking? or am I wrong in thinking that? For example: >>> [1,2,3, *[4,5,6]] File…
Har
  • 3,727
  • 10
  • 41
  • 75
31
votes
4 answers

Why is it valid to assign to an empty list but not to an empty tuple?

This came up in a recent PyCon talk. The statement [] = [] does nothing meaningful, but it does not throw an exception either. I have the feeling this must be due to unpacking rules. You can do tuple unpacking with lists too, e.g., [a, b] = [1,…
j0ker
  • 4,069
  • 4
  • 43
  • 65
30
votes
5 answers

Extended tuple unpacking in Python 2

Is it possible to simulate extended tuple unpacking in Python 2? Specifically, I have a for loop: for a, b, c in mylist: which works fine when mylist is a list of tuples of size three. I want the same for loop to work if I pass in a list of size…
Neil G
  • 32,138
  • 39
  • 156
  • 257
29
votes
2 answers

Is there a more elegant way for unpacking keys and values of a dictionary into two lists, without losing consistence?

What I came up with is: keys, values = zip(*[(key, value) for (key, value) in my_dict.iteritems()]) But I am not satisfied. What do the pythonistas say?
Aufwind
  • 25,310
  • 38
  • 109
  • 154
29
votes
2 answers

Unpacking: [x,y], (x,y), x,y - what is the difference?

What is the difference in Python between unpacking a function call with [], with () or with nothing? def f(): return 0, 1 a, b = f() # 1 [a, b] = f() # 2 (a, b) = f() # 3
rafoo
  • 1,506
  • 10
  • 17
28
votes
5 answers

Tuples and unpacking assignment support in C#?

In Python I can write def myMethod(): #some work to find the row and col return (row, col) row, col = myMethod() mylist[row][col] # do work on this element But in C# I find myself writing out int[] MyMethod() { // some work to find…
jb.
  • 9,921
  • 12
  • 54
  • 90
28
votes
4 answers

Split tuple items to separate variables

I have tuple in Python that looks like this: tuple = ('sparkbrowser.com', 0, 'http://facebook.com/sparkbrowser', 'Facebook') and I wanna split it out so I could get every item from tuple independent so I could do something like this: domain =…
dzordz
  • 2,277
  • 13
  • 51
  • 74
28
votes
8 answers

Is 'shift' evil for processing Perl subroutine parameters?

I'm frequently using shift to unpack function parameters: sub my_sub { my $self = shift; my $params = shift; .... } However, many on my colleagues are preaching that shift is actually evil. Could you explain why I should prefer sub…
Nikolai Prokoschenko
  • 8,465
  • 11
  • 58
  • 97
28
votes
6 answers

Semantics of tuple unpacking in python

Why does python only allow named arguments to follow a tuple unpacking expression in a function call? >>> def f(a,b,c): ... print a, b, c ... >>> f(*(1,2),3) File "", line 1 SyntaxError: only named arguments may follow *expression Is…
user545424
  • 15,713
  • 11
  • 56
  • 70
26
votes
2 answers

Split list into different variables

I have a list like this: [('love', 'yes', 'no'), ('valentine', 'no', 'yes'), ('day', 'yes','yes')] How do I split this list into three variables where each variable holds one tuple, i.e. var1 = ('love', 'yes', 'no') var2 = ('valentine', 'no',…
Eagle
  • 1,187
  • 5
  • 22
  • 40
25
votes
3 answers

`x = y, z` comma assignment in JavaScript

Possible Duplicate: Javascript syntax: what comma means? I came across the code while reading this article (do a Ctrl+F search for Andre Breton): //function returning array of `umbrella` fibonacci numbers function Colette(umbrella) { var…
24
votes
2 answers

How can I explode a tuple so that it can be passed as a parameter list?

Let's say I have a method definition like this: def myMethod(a, b, c, d, e) Then, I have a variable and a tuple like this: myVariable = 1 myTuple = (2, 3, 4, 5) Is there a way I can pass explode the tuple so that I can pass its members as…
froadie
  • 79,995
  • 75
  • 166
  • 235
23
votes
6 answers

What is scheme's equivalent of tuple unpacking?

In Python, I can do something like this: t = (1, 2) a, b = t ...and a will be 1 and b will be 2. Suppose I have a list '(1 2) in Scheme. Is there any way to do something similar with let? If it makes a difference, I'm using Racket.
Jason Baker
  • 192,085
  • 135
  • 376
  • 510
21
votes
4 answers

Is it possible to assign a default value when unpacking?

I have the following: >>> myString = "has spaces" >>> first, second = myString.split() >>> myString = "doesNotHaveSpaces" >>> first, second = myString.split() Traceback (most recent call last): File "", line 1, in ValueError: need…
neverendingqs
  • 4,006
  • 3
  • 29
  • 57
20
votes
4 answers

Returning tuple with a single item from a function

Just came across this little bit of weirdness in Python and thought I'd document it write it as a question here in case anyone else is trying to find an answer with the same fruitless search terms I was Looks like tuple unpacking makes it so you…
mcstrother
  • 6,867
  • 5
  • 22
  • 18
1 2
3
31 32