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
6
votes
3 answers

How to unpack dict with one key-value pair to two variables more elegantly?

Currently, I'm using this: d = {'a': 'xyz'} k, v = list(*d.items()) The starred expression is required here, as omitting it causes the list function/constructor to return a list with a single tuple, which contains the key and value. However, I was…
m01010011
  • 895
  • 8
  • 13
6
votes
5 answers

Pythonic way to unpack an iterator inside of a list

I'm trying to figure out what is the pythonic way to unpack an iterator inside of a list. For example: my_iterator = zip([1, 2, 3, 4], [1, 2, 3, 4]) I have come with the following ways to unpack my iterator inside of a list: 1) my_list =…
kederrac
  • 16,819
  • 6
  • 32
  • 55
6
votes
4 answers

How to unpack an object as it was a tuple in a for loop?

I tried create the following code: class Test(object): def __init__(self, arg): self.arg1 = arg + 1 self.arg2 = arg + 2 self.arg3 = arg + 3 def __iter__(self): return self def __next__(self): …
Evandro Coan
  • 8,560
  • 11
  • 83
  • 144
6
votes
3 answers

Unpacking array/collection in Java

In Python and C#, if you have a tuple/list you can unpack it with the following: tup = (1, 3) a, b = tup Then a = 1 and b = 3. It seems to me that Java doesn't have tuples, but if I have a Vector or primitive [] array of known size, is there a…
shayaan
  • 1,482
  • 1
  • 15
  • 32
6
votes
1 answer

Why does *x, unpack map objects in python 3?

In Python 3, the following returns a map object: map(lambda x: x**2, range(10)) If we want to turn this object into a list, we can just cast it as a list using list(mapobject). However, I discovered through code golfing that *x, = mapobject makes…
Sandeep Silwal
  • 321
  • 5
  • 10
6
votes
3 answers

How to ignore unpacked parts of a tuple as argument of a lambda?

In Python, by convention, the underscore (_) is often used to throw away parts of an unpacked tuple, like so >>> tup = (1,2,3) >>> meaningfulVariableName,_,_ = tup >>> meaningfulVariableName 1 I'm trying to do the same for a tuple argument of a…
Julian
  • 4,170
  • 4
  • 20
  • 27
6
votes
3 answers

Safely unpacking results of str.split

I've often been frustrated by the lack of flexibility in Python's iterable unpacking. Take the following example: a, b = "This is a string".split(" ", 1) Works fine. a contains "This" and b contains "is a string", just as expected. Now let's try…
squirl
  • 1,636
  • 1
  • 16
  • 30
6
votes
2 answers

Handling empty case with tuple filtering and unpacking

I have a situation with some parallel lists that need to be filtered based on the values in one of the lists. Sometimes I write something like this to filter them: lista = [1, 2, 3] listb = [7, 8, 9] filtered_a, filtered_b = zip(*[(a, b) for (a, b)…
Justin
  • 6,611
  • 3
  • 36
  • 57
6
votes
1 answer

star unpacking for own classes

I was wondering if it's possible to use star unpacking with own classes rather than just builtins like list and tuple. class Agent(object): def __init__(self, cards): self.cards = cards def __len__(self): return…
Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69
6
votes
3 answers

Python: Assign variables from array

I have some code in Python: repost_pid = row[0] repost_permalink = row[1] repost_domain = row[2] repost_title = row[3] repost_submitter = row[4] Is there a one-liner way to assign these variables? Also, what would I do if I wanted to skip a value?
Bijan
  • 7,737
  • 18
  • 89
  • 149
6
votes
1 answer

How to unpack a tuple into more values than the tuple has?

I have a list of tuples, each of which contains between 1 to 5 elements. I'd like to unpack these tuples into five values but that won't work for tuples of less than five elements: >>> t = (1,2) # or (1) or (1,2,3) or ... >>> a,b,c,d,e =…
Jens
  • 8,423
  • 9
  • 58
  • 78
6
votes
1 answer

How to unpack a function-returned tuple?

I want to append a table with a list of function-returned values, some of them are tuples: def get_foo_bar(): # do stuff return 'foo', 'bar' def get_apple(): # do stuff return 'apple' table = list() table.append([get_foo_bar(),…
rypel
  • 4,686
  • 2
  • 25
  • 36
5
votes
2 answers

fst and 3-tuple in fsharp

Do you know the nicest way to make this work : let toTableau2D (seqinit:seq<'a*'b*'c>) = let myfst = fun (a,b,c) -> a let myscd = fun (a,b,c) -> b let mytrd = fun (a,b,c) -> c let inputd = seqinit |> groupBy2 myfst myscd there must be…
nicolas
  • 9,549
  • 3
  • 39
  • 83
5
votes
5 answers

Wildcards in Python?

Over the years I have noticed the 'wildcard' variable in various bits and pieces of Python I've come across. I assumed it worked like Haskell: allowing you to put a variable where one was required in the formal parameters, but not binding it. I've…
Joe
  • 46,419
  • 33
  • 155
  • 245
5
votes
1 answer

Is there a way to test if an Iterable contains a pattern using python's "match" statement?

This has to do with the new Python 3.10 beta and the new match syntax. Is there any way to check if a pattern is simply contained in an iterable? the most obvious solution, to simply put two wildcards on either side, but that raises a SyntaxError…