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
20
votes
1 answer

asterisk in tuple, list and set definitions, double asterisk in dict definition

I'm playing now with Python 3.5 interpreter and found very interesting behavior: >>> (1,2,3,"a",*("oi", "oi")*3) (1, 2, 3, 'a', 'oi', 'oi', 'oi', 'oi', 'oi', 'oi') >>> [1,2,3,"a",*range(10)] [1, 2, 3, 'a', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>…
George Sovetov
  • 4,942
  • 5
  • 36
  • 57
19
votes
1 answer

Star * operator on left vs right side of an assignment statement

This questions stems from PEP 448 -- Additional Unpacking Generalizations and is present in Python 3.5 as far as I'm aware (and not back-ported to 2.x). Specifically, in the section Disadvantages, the following is noted: Whilst *elements, =…
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
19
votes
1 answer

Unpack 1 variable, rest to a list

I was wondering if this was possible: def someFunction(): return list(range(5)) first, rest = someFunction() print(first) # 0 print(rest) # [1,2,3,4] I know it could be accomplished with these 3 lines: result = someFunction() first =…
Bartlomiej Lewandowski
  • 10,771
  • 14
  • 44
  • 75
18
votes
1 answer

How are python's unpacking operators * and ** used?

The unpacking/splat operators * and ** differ widely in their applicability across python versions (2.7, 3.x < 3.5 and 3.x >= 3.5). For example: | 2.7 | 3.1-3.4 | 3.5 …
cs95
  • 379,657
  • 97
  • 704
  • 746
18
votes
5 answers

How to unpack a tuple from left to right?

Is there a clean/simple way to unpack a Python tuple on the right hand side from left to right? For example for j = 1,2,3,4,5,6,7 (1,2,3,4,5,6,7) v,b,n = j[4:7] Can I modify the slice notation so that v = j[6], b=j[5], n=j[4] ? I realise I…
18
votes
2 answers

What is with this change of unpacking behavior from Python2 to Python3

Yesterday I came across this odd unpacking difference between Python 2 and Python 3, and did not seem to find any explanation after a quick Google search. Python 2.7.8 a = 257 b = 257 a is b # False a, b = 257, 257 a is b # False Python 3.4.2 a =…
18
votes
2 answers

Change what the *splat and **splatty-splat operators do to my object

How do you override the result of unpacking syntax *obj and **obj? For example, can you somehow create an object thing which behaves like this: >>> [*thing] ['a', 'b', 'c'] >>> [x for x in thing] ['d', 'e', 'f'] >>> {**thing} {'hello world': 'I am a…
wim
  • 338,267
  • 99
  • 616
  • 750
18
votes
3 answers

Is there a javascript equivalent to unpack sequences like in python?

Is there a javascript equivalent to unpack sequences like in python? a, b = (1, 2)
tback
  • 11,138
  • 7
  • 47
  • 71
17
votes
2 answers

Common Lisp -- List unpacking? (similar to Python)

In Python, assuming the following function is defined: def function(a, b, c): ... do stuff with a, b, c ... I am able to use the function using Python's sequence unpacking: arguments = (1, 2, 3) function(*arguments) Does similar functionality…
brildum
  • 1,759
  • 2
  • 15
  • 22
17
votes
3 answers

Unpack to unknown number of variables?

How could I unpack a tuple of unknown to, say, a list? I have a number of columns of data and they get split up into a tuple by some function. I want to unpack this tuple to variables but I do not know how many columns I will have. Is there any way…
Nope
  • 34,682
  • 42
  • 94
  • 119
17
votes
4 answers

Scala: Unpacking tuple as part of argument list

I am trying to send the result of a method call's tuple, as part of the argument list for another method. Target method def printResult(title: String, result: Int, startTime: Long, endTime: Long) Return from method, partial argument list def…
Hanxue
  • 12,243
  • 18
  • 88
  • 130
16
votes
6 answers

Is there way to create tuple from list(without codegeneration)?

Sometimes there are needs to create tuples from small collections(for example scalding framework). def toTuple(list:List[Any]):scala.Product = ...
yura
  • 14,489
  • 21
  • 77
  • 126
15
votes
5 answers

Swapping Columns with NumPy arrays

When I have a=1 and b=2, I can write a,b=b,a so that a and b are interchanged with each other. I use this matrix as an array: [ 1, 2, 0, -2] [ 0, 0, 1, 2] [ 0, 0, 0, 0] Swapping the columns of a numpy array does not work: import…
Xiphias
  • 4,468
  • 4
  • 28
  • 51
14
votes
3 answers

Unpack python tuple with [ ]'s

I know the canonical way to unpack a tuple is like this a, b, c = (1, 2, 3) # or (a,b,c) = (1, 2, 3) but noticed that you can unpack a tuple like this [a, b, c] = (1, 2, 3) Does the second method incur any extra cost due to some sort of cast or…
Philip Nelson
  • 1,027
  • 12
  • 28
14
votes
3 answers

Python: Formatting a string using variable names placeholders

Consider the following string building statement: s="svn cp %s/%s/ %s/%s/" % (root_dir, trunk, root_dir, tag) Using four %s can be confusing, so I prefer using variable names: s="svn cp {root_dir}/{trunk}/…
Adam Matan
  • 128,757
  • 147
  • 397
  • 562