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
0
votes
0 answers

How do I get this tuple to compute with my function?

def heat_transfer(enter_temperature, leave_temperature, flow_rate) : enter_temperature -= leave_temperature temp_change = enter_temperature C = 4.19 density = 1 Q = (flow_rate * density) * C * temp_change return…
0
votes
1 answer

Unpacking tuple after regression by group in python

I am running regressions by group. I am outputting coefficients and the entire vector of residuals for each group. This results in a tuple with differently sized "elements”. Currently I am having trouble unpacking it into two separate, workable data…
0
votes
1 answer

How Python 3 zip list/tuple unpacking works under the hood?

I am learning Python 3 and I saw that you can zip 2 lists together, like this: l1 = [1,2,3] l2 = ['a','b','c'] l3 = zip(l1,l2) print(list(zip_L1L2)) # Output: [(1, 'a'), (2, 'b'), (3, 'c')] And then reverse the process like that: l4, l5 =…
Ailete619
  • 194
  • 1
  • 18
0
votes
1 answer

How to pass all elements of a sequence to a function in Python?

Or equivalently, how to unpack elements of a sequence of variable length? I'm trying to write a function to return the Cartesian product of all the tuples inside a list (the list has a variable length): Input: [(1, 2), (3,), (5, 0)] Output: [(1, 3,…
Righter
  • 111
  • 4
0
votes
1 answer

C# lambdas with list as parameters

Selecting from a list of lists in a lambda expression, I access the elements with ElementAt. However, it would be nicer to have the elements of my list directly as parameters for my lamda expression: using System.Linq; using…
user1981275
  • 13,002
  • 8
  • 72
  • 101
0
votes
1 answer

Does * Unpacking Use Memory on Generator Expression?

Example for context: Does calling * to unpack input put everything into memory? I'm hoping not but just want to confirm my understanding. input = (x for x in ((1, 'abc'), (2, 'def'))) # generator expression unzipped = zip(*input) # Does *input get…
0
votes
0 answers

Unpacking a tuple within a list using spaCy's char_span

I have a dict that looks like this: TRAIN_DATA = {'here is some text': [('1', '4', 'entity_label')], 'here is more text': [('2', '7', 'entity_label_2')], 'and even more text': [('1', '4', 'entity_label')]} I'm trying to convert this to the format…
Salted
  • 9
  • 2
0
votes
0 answers

How to print unpacked iterable or string?

I am trying to print a unpacked iterable, or a string if said iterable is empty in Python 3.9 (also happens in 3.10), and I am getting some unexpected behavior. print is applying the star operator to the whole Iterable or str expression, regardless…
0
votes
1 answer

Unpack `np.unravel_index()` in for loop

I'm trying to directly unpack the tuple returned from np.unravel_index() in a for loop definition, but I'm running into the following issue: for i,j in np.unravel_index(range(len(10)), (2, 5)): print(i,j) returns: ValueError: too many values to…
Thomas Tiotto
  • 379
  • 1
  • 3
  • 12
0
votes
1 answer

Iterable-Unpack Causing Problem With Later Function Call Can't Get to Work

Below is a portion of my Python code for a Blackjack project. I am using the portion of code for testing because I think I finally narrowed down where the problem is but I just can't figure out how to get it work. The problem seems to be that when I…
Barry Brewer
  • 63
  • 1
  • 5
0
votes
1 answer

Unpacking a list of dictionaries to get all their keys

I am writing a script to add missing keys within a list of dictionaries and assign them a default value. I start by building a set of all the possible keys that appear in one or more dictionaries. I adapted a nice snippet of code for this but I'm…
arsalanQ
  • 127
  • 6
0
votes
1 answer

Can I use a pre-defined tuple for dynamic tuple unpacking in for loops?

I am currently working on building a piece of code that is composing business objects from tuples that it has been given by the data source I am using. Since these tuples may vary in length and their naming, I want to insert a pre-defined tuple into…
0
votes
0 answers

ValueError error in Python "too many values to unpack (expected 2)" when calling a function with multiple arguments

I have 2 Python files and in the first one I am calling a function from the second one. However, I always get the error "ValueError: too many values to unpack (expected 2)" and I don't know why I get it. The function in the second files takes 16…
PeterBe
  • 700
  • 1
  • 17
  • 37
0
votes
1 answer

unpacking * is throwing syntax error on leetcode

I am solving the coin change problem. I run code on jupyter-notebook with the given example on leetcode and it works. The same code does not work on leetcode. causing syntax error: Here is the code to copy: def best_sum(target,nums): dp=[None…
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
0
votes
1 answer

what exactly happens if I set two parameter in for statement?

lst = ['first', 'second'] for q,w in lst: print(q) print(w) If I set my code like this, the result is an error. But if I do this way: lst = [['first', 'second']] for q,w in lst: print(q) print(w) The output is #first #second . I…
gorang2
  • 49
  • 4