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
1
vote
2 answers

Additional Unpacking Generalizations (PEP 448) with variable number of elements

The acceptance of PEP 448 has introduced Additional Unpacking Generalizations in Python 3.5. For example: >>> l1 = [1, 2, 3] >>> l2 = [4, 5, 6] # unpack both iterables in a list literal >>> joinedList = [*l1, *l2] >>> print(joinedList) [1, 2, 3, 4,…
Jean-Francois T.
  • 11,549
  • 7
  • 68
  • 107
1
vote
1 answer

Unpack DataFrame with tuple entries into separate DataFrames

I wrote a small class to compute some statistics through bootstrap without replacement. For those not familiar with this technique, you get n random subsamples of some data, compute the desired statistic (lets say the median) on each subsample, and…
lucianopaz
  • 1,212
  • 10
  • 17
1
vote
1 answer

Iterable Unpacking Evaluation Order

I recently answered a question where a user was having trouble because they were appending a multi-dimensional array to another array, and it was brought to my attention in my answer that it is possible to use iterable unpacking to populate an x and…
Nick is tired
  • 6,860
  • 20
  • 39
  • 51
1
vote
1 answer

Efficiently unpack CSV columns into separate lists

I am optimizing my script and find this problem: Here I have a csv file where the first column is just index and the second column contains a string (sentence of arbitrary length). I want to create two variables "index" and "string" that contains…
Yi Shen
  • 108
  • 1
  • 10
1
vote
3 answers

Iterate over list of NumPy matrices

I've got a list with row matrices: rows = [ matrix([[1, 0, 0]]), matrix([[0, 1, 0]]), matrix([[0, 0, 1]]) ] and I attempted to loop over these using for (a, b, c) in rows:, but instead of this working, I got an error: ValueError: not enough values…
Frank Vel
  • 1,202
  • 1
  • 13
  • 27
1
vote
2 answers

Why is the result different if I switch the sequence in setting variables by common?

To explain better, I wrote a small class node, and set a and b: class node(object): def __init__(self,x,y): self.val = x self.next = y a = node(5,6) b = None Then I found the result is different between: a, a.next, b = a.next,…
Root
  • 97
  • 1
  • 12
1
vote
2 answers

What's wrong with here? Python2 ->Python3

I'm practicing Python with the book called Learn "Python The Hard Way 3rd edition". I searched that this book is a good resource to get a start. from sys import argv script, first, second, third = argv print('The script is called: '+ script) print…
Oliver Bird
  • 145
  • 2
  • 15
1
vote
1 answer

Why can't list unpacking be used for indexing a second list?

… e.g. a[*b] where a and b are both lists and len(b) == 1 Using the simple example below: a = [1,2,3,4] b = [0] a[*b] Why does running the above raise an exception? a[*b] ^ SyntaxError: invalid syntax
Greg
  • 8,175
  • 16
  • 72
  • 125
1
vote
1 answer

Unpack Tuple within dictionary

Why isn't this unpacking work for my dictionary? The dictionary is build as follows: cutDict = {'scene1': [('scene3', 1001, 1125)]} I'm trying to unpack this like: for key, (cut, fIn, fOut) in cutDict.iteritems(): print key print cut …
Petter Östergren
  • 973
  • 4
  • 14
  • 27
1
vote
4 answers

fancy Dictionary Unpacking

I have a dictionary as such: test = {'tuple':(1, 2, 3, 4), 'string':'foo', 'integer':5} In order to keep down wasted space, I'd like to unpack these values into individual variables. I know that it is possible to unpack the keys of a…
James Wright
  • 1,293
  • 2
  • 16
  • 32
1
vote
1 answer

Why does unpacking a chain with a non-iterable argument raise this error?

Consider the following code: from itertools import chain list(chain(42)) I am passing a non-iterable as an argument to chain and little surprisingly, I get exactly this error: TypeError: 'int' object is not iterable (Passing to list is only…
Wrzlprmft
  • 4,234
  • 1
  • 28
  • 54
1
vote
2 answers

Expand tuple into arguments while casting them?

I have this: blah = random.randint(int(minmax[0]), int(minmax[1])) I know this is possible: minimum, maximum = int(minmax[0]), int(minmax[1]) blah = random.randint(minimum, maximum) Can I do this second one in a single line using tuple-argument…
MaxStrange
  • 137
  • 1
  • 10
1
vote
0 answers

Iterable unpacking cannot be used in comprehension (Python 3 `*` operator)

I have a pd.Series that contains str representations of sets. I want to use iterable unpacking to empty all of these lists into a single container (intuitively, the syntax makes perfect sense). I'm running 3.5.2 right now. import pandas as…
O.rka
  • 29,847
  • 68
  • 194
  • 309
1
vote
2 answers

map of function list and arguments: unpacking difficulty

I have an assignment in a mooc where I have to code a function that returns the cumulative sum, cumulative product, max and min of an input list. This part of the course was about functional programming, so I wanted to go all out on this, even…
Ando Jurai
  • 1,003
  • 2
  • 14
  • 29
1
vote
2 answers

How do I yield a pre-unpacked list?

I have a list that is created within an itertools.groupby operation: def yield_unpacked_list(): for key, grp in itertools.groupby(something_to_groupby, key=lambda x: x[0]): subset_of_grp = list(item[2] for item in list(grp)) …
Kit
  • 30,365
  • 39
  • 105
  • 149