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
1 answer

How to Pass arguments to fit() using a for loop?

I'm trying to train a classification model on 10 different training sets, I tried using a for loop to iterate the sets names in a dictionary then pass them in fit() method in each iteration. Here is the code: for n in range (1, 11): classifier =…
0
votes
2 answers

unpack to int and string in python

Is there a way to unpack to diferent types? this is the case: # data = [4, "lorem", "ipsum", "dolor", "sit", "amet"] (parts, *words) = data data is provided. I never assign this value. I add as example. parts must be an int, all the rest of the…
0
votes
5 answers

How to fix ValueError: too many values to unpack (expected 3) in Python?

I have a dataset called records, a dataset sample looks like: user_id movie_id genre 1 1001 action 2 1002 drama 3 1003 comedy 4 1004 drama ... ... ... I would like to iterate over records in the…
Azamat
  • 209
  • 1
  • 3
  • 10
0
votes
1 answer

Python Django Template language unpack List

I am trying to pass values from the views.py to the HTML to be displayed but a list is being passed instead of a single value. I have a random link that should randomly pick an item from the list, this is the HTML where the item should link to
Bijin Abraham
  • 1,709
  • 2
  • 11
  • 25
0
votes
1 answer

Getting an error like TypeError: cannot unpack non-iterable float object

Am computing the cost, but facing the error as TypeError: cannot unpack non-iterable float object #Compute cost def compute_cost(A2,y,parameters): m=y.shape[0] logprobs = y*np.log(A2) + (1-y)*np.log(1-A2) cost = -1/m*np.sum(logprobs) …
jade
  • 17
  • 1
  • 7
0
votes
0 answers

Nested Tuple Unpacking with Strings

I am trying to write a function that takes a nested tuple of strings and returns another tuple that contains all items of the original one, but "unpacked". For example: my_hobbies = ('reading', ('jogging', 'boxing', 'yoga'),…
0
votes
2 answers

Python ValueError: not enough values to unpack (expected 2, got 1)

In my text file i have Strings data i am try to unpack them using Split() but unfortunately giving me error as "ValueError: not enough values to unpack (expected 2, got 1)" Plz help to solve me if you know with open('Documents\\emotion.txt', 'r') as…
user12498867
  • 1
  • 1
  • 3
0
votes
3 answers

Python convert a list of 4 tuple into three 2 tuples, joined on the last element in the tuple

From a django query values_list() I have a list of 4 tuples, ie [('AAA', '123', 'xyz', '111'), ('BBB', '456', 'uvw', '222'), ...] What I Want is a multiple lists of two tuples, joined on the last element of each tuple, ie [('AAA', '111'), ('BBB',…
wil moskal
  • 309
  • 1
  • 14
0
votes
0 answers

TypeError: cannot unpack non-iterable NoneType object while using operator packages

import operator class Point(): def __init__(self,x,y): self.x=x self.y=y def __repr__(self): return '<{0},{1}>'.format(self.x,self.y) def distance(a,b): return abs((a.x-b.x)**2+(a.y-b.y)**2)**.5 def…
0
votes
1 answer

How to unpack result of `zip` which might be empty?

I have a generator for tuples which I want to use like this: def pairs(): yield from [("key1", 2), ("key2", 4), ("key3", 6)] keys, values = zip(*pairs()) Works like a charm, but now pairs() can also yield nothing resulting in an expression…
frans
  • 8,868
  • 11
  • 58
  • 132
0
votes
2 answers

Python: Adding unpacked values (strings) of a tuple

Is there a single line command to add two strings contained in a tuple to two existing strings in a program? This is essentially what I want to do but in a shorter way, t=("hi","hello") x="test" y="python" x+=t[0] y+=t[1] I was thinking maybe there…
Hiya
  • 21
  • 3
0
votes
1 answer

Used tuple unpacking in Python, can't figure out the logical error

Can't seem to figure out the problem here : I'm passing a list vote_sort([("TOD",12),("Football",20),("Baseball",19),("Tennis",10)]) The output that i'm getting [('Baseball', 19), ('Football', 20), ('TOD', 12), ('Tennis', 10)] Desired Output :…
dbridgedev
  • 48
  • 5
0
votes
1 answer

How to return different count of multiple values from Python function

I have legacy class hierarchy which I want to extend with new class with different method signature: overrided method should return tree values instead of two. Third return value for legacy classes should be some default value. Example below…
feeeper
  • 2,865
  • 4
  • 28
  • 42
0
votes
2 answers

Python tuple unpack problem

sendnpc = (npc2alive,Orinpc3,Posnpc3) Data = dumps((PosYou,OriYou,Shoot,txtt,Posnpc,Orinpc,npcalive,Posnpc2,Orinpc2,sendnpc)) I'm sending this material to another computer, the problem is when I'm unpacking it. The unpacking part of the script…
eson
  • 1