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
14
votes
2 answers

Python-like unpacking of numeric value in R

In Python, one can do this: >>> a, b, c = (1, 2, 3) >>> a 1 >>> b 2 >>> c 3 Is there a way to do it in R, as below? > a, b, c = c(1, 2, 3)
brandizzi
  • 26,083
  • 8
  • 103
  • 158
14
votes
8 answers

Python - tuple unpacking in dict comprehension

I'm trying to write a function that turns strings of the form 'A=5, b=7' into a dict {'A': 5, 'b': 7}. The following code snippets are what happen inside the main for loop - they turn a single part of the string into a single dict element. This is…
13
votes
1 answer

Is there a way to splat-assign as tuple instead of list when unpacking?

I was recently surprised to find that the "splat" (unary *) operator always captures slices as a list during item unpacking, even when the sequence being unpacked has another type: >>> x, *y, z = tuple(range(5)) >>> y [1, 2, 3] # list, was…
ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
13
votes
3 answers

Tuple Unpacking Similar to Python, but in Common Lisp

Is there a way to assign the values of a list to a list of symbols in Common Lisp similar to the way that you can assign the values of tuple to variables in Python? x, y, z = (1, 2, 3) Something like (setq '(n p) '(1 2)) Where n and p are now…
Phillip Cloud
  • 24,919
  • 11
  • 68
  • 88
13
votes
2 answers

How to unpack a list of tuples with enumerate?

I stumbled upon an unpack issue I can not explain. This works: tuples = [('Jhon', 1), ('Jane', 2)] for name, score in tuples: ... This also works for id, entry in enumerate(tuples): name, score = entry ... but this does not work: for…
Finn
  • 1,999
  • 2
  • 24
  • 29
13
votes
5 answers

Idiomatic way to unpack variable length list of maximum size n

I'm reading a file and unpacking each line like this: for line in filter(fh): a, b, c, d = line.split() However, it's possible that line may have more or fewer columns than the variables I wish to unpack. In the case when there are fewer, I'd…
pythonic metaphor
  • 10,296
  • 18
  • 68
  • 110
12
votes
2 answers

TypeError: () missing 1 required positional argument: 'w'

Code is here return self.activator(reduce(lambda a, b: a+b, map(lambda x, w: x*w, zip(input_vec, self.weights)), 0.0) + self.bias) The python2.7-version code is like lambda (x, w) But now the Tuple parameter unpacking was removed so I dont know how…
yizhuo liu
  • 123
  • 1
  • 1
  • 4
12
votes
3 answers

Python Tuple Unpacking

If I have nums_and_words = [(1, 'one'), (2, 'two'), (3, 'three')] and would like nums = [1, 2, 3] words= ['one', 'two', 'three'] How would I do that in a Pythonic way? It took me a minute to realize why the following doesn't work nums, words =…
Raphi
  • 410
  • 4
  • 17
12
votes
3 answers

Python swapping lists

In python, when I assign a list to another, like: a = [1,2,3] b = a Now b and a point to the same list. Now considering two lists, a = [1,2,3] b = [4,5,6] a,b = b,a Now how is it that they are swapped like any other data type and does not end up…
Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
12
votes
3 answers

Invalid syntax python starred expressions

I am trying to unpack set of phone numbers from a sequence, python shell in turn throws an invalid syntax error. I am using python 2.7.1. Here is the snippet >>> record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212') >>> name,…
user2385591
  • 121
  • 1
  • 1
  • 3
11
votes
4 answers

Python-like list unpacking in C#?

In python, I can do something like this: List=[3, 4] def Add(x, y): return x + y Add(*List) #7 Is there any way to do this or something similar in C#? Basically I want to be able to pass a List of arguments to an arbitrary function, and have…
ryeguy
  • 65,519
  • 58
  • 198
  • 260
11
votes
4 answers

ValueError: too many values to unpack (expected 2)

In the Python tutorial book I'm using, I typed an example given for simultaneous assignment. I get the aforementioned ValueError when I run the program, and can't figure out why. Here's the code: #avg2.py #A simple program to average two exam…
Ziggy
  • 365
  • 2
  • 5
  • 13
11
votes
1 answer

Scala: Parallel assignment of Tuples

Is it possible to assign tuple members in parallel in Scala. if not is there another technique to accomplish something similar? val players = List( new Player("Django Reinhardt", 42), new Player("Sol Hoopii", 57), new Player("Marc…
BefittingTheorem
  • 10,459
  • 15
  • 69
  • 96
11
votes
1 answer

Is it possible to unpack a tuple without using variables?

I'm using the os.path.split() function on a path in my program to get the filename and pathname of a file then passing them into another method, but my current solution seems rather ugly: path = os.path.split(somefile) some_class(path[0],…
ghickman
  • 5,893
  • 9
  • 42
  • 51
11
votes
3 answers

python: when can I unpack a generator?

How does it work under the hood? I don't understand the reason for the errors below: >>> def f(): ... yield 1,2 ... yield 3,4 ... >>> *f() File "", line 1 *f() ^ SyntaxError: invalid syntax >>> zip(*f()) [(1, 3), (2, 4)] >>>…
Rusty Rob
  • 16,489
  • 8
  • 100
  • 116