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

Subsetting a vector using another boolean vector in R

Using the following two R vectors, I want to extract a subset of valMe using the boolean values in boolMe. In addition, I would like to have two possible outputs, one where the FALSE values in boolMe are ommited from valMe, and one where the FALSE…
hhh
  • 50,788
  • 62
  • 179
  • 282
10
votes
2 answers

Why does starred assignment produce lists and not tuples?

In python, I can write something like this: some_list = [(1, 2, 3), (3, 2, 1)] for i, *args in some_list: print(args) I will get the next output: [2, 3] [2, 1] When we use *args as function arguments, it is unpacked into a tuple. Why do we…
EdiBoba
  • 103
  • 4
10
votes
4 answers

Will tuple unpacking be directly supported in parameter lists in Scala?

In Haskell you can write: x :: (Int,Int) -> Int x (p,s) = p In Scala you would write: def x(a: (Int, Int)) = a._1 or: def x(a: (Int, Int)) = a match { case (p, s) => p } Why not have something like def x(_: (p: Int, s: Int)) = p or def…
letmaik
  • 3,348
  • 1
  • 36
  • 43
10
votes
4 answers

Unpacking object variables in python

I'm thinking if there is some way to unpack object attributes. Usually doing this involves series of: self.x = x self.y = y ... #etc. However it should be possible to do it better. I'm thinking about something like: def __init__(self,x,y,z): …
yatsek
  • 855
  • 1
  • 10
  • 19
10
votes
1 answer

How exception-safe is std::tie?

std::tie returns a tuple of references, so you can do the following: int foo, bar, baz; std::tie(foo, bar, baz) = std::make_tuple(1, 2, 3); This is similar to foo, bar, baz = (1, 2, 3) in Python. What is supposed to happen if one of the assignments…
user142019
9
votes
2 answers

Is there an alternative for zip(*iterable) when the iterable consists of millions of elements?

I have come across a code like this: from random import randint class Point: def __init__(self, x, y): self.x = x self.y = y points = [Point(randint(1, 10), randint(1, 10)) for _ in range(10)] xs = [point.x for point in…
Asocia
  • 5,935
  • 2
  • 21
  • 46
9
votes
1 answer

Why does unpacking give a list instead of a tuple in Python?

This is really strange to me, because by default I thought unpacking gives tuples. In my case I want to use the prefix keys for caching, so a tuple is preferred. # The r.h.s is a tuple, equivalent to (True, True, 100) *prefix, seed =…
episodeyang
  • 642
  • 8
  • 15
9
votes
3 answers

Unpack value(s) into variable(s) or None (ValueError: not enough values to unpack)

How should an iterable be unpacked into a mismatching number of variable(s)? Too many values: >>> one,two = [1,2,3] Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack (expected 2) can be…
handle
  • 5,859
  • 3
  • 54
  • 82
9
votes
3 answers

Unpacking a 1-tuple in a list of length 1

Suppose I have a tuple in a list like this: >>> t = [("asdf", )] I know that the list always contains one 1-tuple. Currently I do this: >>> dummy, = t >>> value, = dummy >>> value 'asdf' Is there a shorter and more elegant way to do this?
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
9
votes
1 answer

vector unpacking for octave

Octave(/matlab)'s notation for handling multiple return values [a, b] = f(x) suggests that the values returned by f(x) are in a sort of row vector and that Octave supports vector unpacking (like Python's tuple-unpacking). Yet when I put [a, b] =…
dspyz
  • 5,280
  • 2
  • 25
  • 63
9
votes
3 answers

Python: Why can't I unpack a tuple into a dictionary?

Why doesn't this work?: d["a"], d["b"] = *("foo","bar") Is there a better way to achieve what I'm trying to achieve?
jsj
  • 9,019
  • 17
  • 58
  • 103
8
votes
7 answers

How To Merge an Arbitrary Number of Tuples in Python?

I have a list of tuples: l=[(1,2,3),(4,5,6)] The list can be of arbitrary length, as can the tuples. I'd like to convert this into a list or tuple of the elements, in the order they appear: f=[1,2,3,4,5,6] # or (1,2,3,4,5,6) If I know the at…
technomalogical
  • 2,982
  • 2
  • 26
  • 43
8
votes
2 answers

Why does Scala construct a new Tuple when unpacking a Tuple?

Why does this Scala code: class Test { def foo: (Int, String) = { (123, "123") } def bar: Unit = { val (i, s) = foo } } generate the following bytecode for bar() that constructs a new Tuple2, passes the Tuple2 from foo() to it…
Blair Zajac
  • 4,555
  • 3
  • 25
  • 36
8
votes
1 answer

How does R evaluate these weird expressions?

I was trying to make Python 3-style assignment unpacking possible in R (e.g., a, *b, c = [1,2,3], "C"), and although I got so close (you can check out my code here), I ultimately ran into a few (weird) problems. My code is meant to work like this: a…
Zeke
  • 617
  • 1
  • 6
  • 15
8
votes
2 answers

Unpacking an array in python

I have a variable data that is of (1000L, 3L) shape and I do the following to get the coordinates: x = data[:,0] y = data[:,1] z = data[:,2] Is there a way to unpack them? I tried but it doesn't work: [x,y,z] = data1[:,0:3]
SEU
  • 1,304
  • 4
  • 15
  • 36