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

How to unpack a dictionary of list (of dictionaries!) and return as grouped tuples?

I have a data structure consisting of mixed dictionaries and lists. I am trying to unpack this so as to get tuples of the keys and all sub-values for each key. I am working with list comprehensions, but just not getting it to work. Where am I going…
Roberto
  • 2,054
  • 4
  • 31
  • 46
8
votes
3 answers

How to unpack optional items from a tuple?

I have a list of some input values, of which the first couple of mandatory and the last couple optional. Is there any easy way to use tuple unpacking to assign these to variables, getting None if the optional parameters are missing. eg. a = [1,2] …
xorsyst
  • 7,897
  • 5
  • 39
  • 58
8
votes
1 answer

Passing a collection argument without unpacking its contents

Question: What are the pros and cons of writing an __init__ that takes a collection directly as an argument, rather than unpacking its contents? Context: I'm writing a class to process data from several fields in a database table. I iterate through…
Air
  • 8,274
  • 2
  • 53
  • 88
7
votes
6 answers

overloading operator << for std::tuple - possible simplications?

I used an answer to the SO question "iterate over tuple" to write a method to overload <<. This method was tested and appears to work correctly with g++ 4.7 on Debian squeeze. However this method is kind of roundabout, since it seems << cannot be…
Faheem Mitha
  • 6,096
  • 7
  • 48
  • 83
7
votes
1 answer

How is Python's iterator unpacking (star unpacking) implemented (or, what magic methods are involved in unpacking a custom iterator?)

I am writing a class that defines __iter__ and __len__, where the value of __len__ depends on the iterator returned by __iter__. I am getting an interesting RecursionError. Language versions: Python 3.8.6, 3.7.6. Examples are for illustrating the…
7
votes
2 answers

Packing values into a tuple using *, just like function argument packing

Consider a function defined as: def fun(a, *args): print(type(args), args) When called, it packs the extra positional arguments as a tuple. >>> fun(2, 3, 4) (3, 4) I want to achieve a similar thing outside of function…
2020
  • 2,821
  • 2
  • 23
  • 40
7
votes
5 answers

What does a single (not double) asterisk * mean when unpacking a dictionary in Python?

Can anyone explain the difference when unpacking the dictionary using a single or a double asterisk? You can mention their difference when used in function parameters, only if it is relevant here, which I don't think so. However, there may be some…
Han XIAO
  • 1,148
  • 9
  • 20
7
votes
0 answers

Why can't iterable unpacking be used in a list comprehension?

When I try to unpack lists in a list comprehension: [*parent.rules for parent in parents if hasattr(parent, "rules")] I get the error: SyntaxError: iterable unpacking cannot be used in comprehension While I understand there are other ways to do…
7
votes
5 answers

Unpack a List in to Indices of another list in python

Is it possible to unpack a list of numbers in to list indices? For example I have a lists with in a list containing numbers like this: a = [[25,26,1,2,23], [15,16,11,12,10]] I need to place them in a pattern so i did something like this newA =…
Watarap
  • 307
  • 3
  • 11
7
votes
3 answers

Default values for iterable unpacking

I've often been frustrated by the lack of flexibility in Python's iterable unpacking. Take the following example: a, b = range(2) Works fine. a contains 0 and b contains 1, just as expected. Now let's try this: a, b = range(1) Now, we get a…
squirl
  • 1,636
  • 1
  • 16
  • 30
7
votes
1 answer

Type conversion for namedtuple fields during initialization

I have a class that has few static fields and is initialized from iterable (like output from csvreader). The __init__ performs type conversion from strings to numbers for some of them: class PerformanceTestResult(object): def __init__(self,…
Palimondo
  • 7,281
  • 4
  • 39
  • 58
7
votes
2 answers

Pandas - Unpack column of lists of varying lengths of tuples

I would like to take a Pandas Dataframe named df which has an ID column and a lists column of lists that have variable number of tuples, all the tuples have the same length. Looks like this: ID list 1 [(0,1,2,3),(1,2,3,4),(2,3,4,NaN)] 2 …
clg4
  • 2,863
  • 6
  • 27
  • 32
7
votes
1 answer

Assigning multiple variables in Haskell

Just getting started in Haskell, and I'm trying to figure out the best way to assign multiple variables based on a single condition. So far I've just been packing and unpacking Tuples. Is there a better/more idiomatic way? (var1, var2, var3) = …
alexp
  • 3,587
  • 3
  • 29
  • 35
7
votes
1 answer

For loop item unpacking

Once, after watching Mike Muller's performance optimization tutorial (I think this one), one thought started to live in my head: if performance matters, minimize accessing items in the loop by index, e. g. if you need to access x[1] multiple times…
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
6
votes
1 answer

Priority of tuple (un)packing with inline if-else

Apologies in advance for the obscure title. I wasn't sure how to phrase what I encountered. Imagine that you have a title of a book alongside its author, separated by -, in a variable title_author. You scraped this information from the web so it…