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

Problems with tuple unpacking

In a function, i'm returning a list of two values if the values are there or an empty list, like below: def func1(prikey): try: df = somesql for index, rW in df.iterrows(): retvalue = [rW['id_in_int'],rW['time_in_str']] …
Ilyas
  • 181
  • 1
  • 1
  • 8
0
votes
1 answer

Finding max frequency of character used in a given string

In the following piece of code I'm trying to find the most used character in a given sentence. I've used list unpacking, and I've seen different ways of solving this. My question is, is this a good way to do it? or it's too complicated and not…
user13059789
0
votes
2 answers

How to a, b = myClass(a, b) in Python?

Python does this: t = (1, 2) x, y = t # x = 1 # y = 2 How can I implement my class so to do class myClass(): def __init__(self, a, b): self.a = a self.b = b mc = myClass(1, 2) x, y = mc # x = 1 # y = 2 Is there a magic…
user12546101
0
votes
1 answer

Error in python: "cannot unpack non-iterable NoneType object"

Alright so, I was just learning a different way of inputting data in python, and tried a function: def userInput(): n1 = float(input("Enter first number: ")) n2 = float(input("Enter second number: ")) n3 = float(input("Enter third…
Saharsh Aanand
  • 109
  • 1
  • 1
  • 2
0
votes
1 answer

How to assign a variable to colorsys output data

I was wondering if/how I could assign a variable to each outputted value from a colorsys conversion. >>conversion = colorsys.rgb_to_hsv(RC, GC, BC) >>print(conversion) >>#outputted data >>(H,S,L) Essentially I would like to use the outputted data…
0
votes
3 answers

What does [None]* means in python

I was recently studying someone's code and a portion of code given below class Node: def __init__(self, height=0, elem=None): self.elem = elem self.next = [None] * height What does it mean by [None] * height in the above code I know what…
Shaida Muhammad
  • 1,428
  • 14
  • 25
0
votes
1 answer

while unpacking a list of lists using zip(*some_list) in a for loop declaration, how do i set up my iterators dynamically?

This is how my code is basically set up, but as you can see p1-p9 is static behavior. What if i dont know how many items will be unpacked from zip(*P)? #What if i dont know how many items are being unpacked with *P? for p_1, p_2, ... p_9 in…
Hassan
  • 1
0
votes
1 answer

Can't unpack tuples when tuple of tuples has single tuple. Why? Works with array of tuples

Why can't a single tuple in an tuple of tuples be unpacked? A single tuple in any array of tuples does work, however. Tuple of Tuples (many tups) --- Works mytup=(([1,2,3],['a','b','c'],99),([2,2,3],['b','b','c'],100)) for t in mytup: …
user3062149
  • 4,173
  • 4
  • 17
  • 26
0
votes
0 answers

Python3 error in unpacking list with fewer variables [a,b,_] in for loop

I am trying to unpack a list with fewer variables and get the following error. human_prots looks like…
View7
  • 1
  • 2
0
votes
0 answers

Dictionary/key word unpacking - must be strings

I have created a function >>> fun(a,b,c): print(a,b,c) Which I can pass a list to, say [1,2,3] by unpacking and we have >>> fun(*[1,2,3]) 1, 2, 3 or I can pass a dictionary d = {1:'a',2:'b',3:'c'} >>> fun(*d) 1, 2, 3 However, I experience a…
RhythmInk
  • 513
  • 1
  • 4
  • 18
0
votes
1 answer

How to make a class act as two element tuple and unpack elements?

Let's say I have a following piece of code (x1, y1), (x2, y2) = foo() class Bar: def __init__(self, x, y): self.x = x self.y = y bar1 = Bar(x1, y1) bar2 = Bar(x2, y2) Is there any way to avoid having x1, x2 etc and unpack is…
hans
  • 1,043
  • 12
  • 33
0
votes
2 answers

Breaking down the loop logic for the below code:

I am trying to understand the below code but I am unable to get the loop section I am new to unpacking records = [('foo',1,2),('bar','hello'),('foo',3,4)] def do_foo(x,y): print('foo',x,y) def do_bar(s): print('bar',s) for tag, *args in…
0
votes
1 answer

How to unpack different values depending on number of variables to unpack into

I'm scratching my head over how to conditionally unpack variables from a class depending on the number of variables you are unpacking into e.g. I get a different set of variables unpacked depending on the number I set on the left hand side of the…
Liam Deacon
  • 904
  • 1
  • 9
  • 25
0
votes
4 answers

Safe unpack empty tuple array

The line import re; print(re.findall("(.*) (.*)", "john smith")) outputs [("john", "smith")], which can be unpacked like [(first_name, last_name)] = re.findall(...). However, in the event of a non-match (findall returning []) this unpacking throws…
Frayt
  • 1,194
  • 2
  • 17
  • 38
0
votes
1 answer

"Too many values to unpack" error when summarizing big text files in python

I have 2 tab separated text file. One of them is called major and the other one is called minor. These are 2 small examples of files: major: chr1 + 1071396 1271396 LOC chr12 + 1101483 1121483 MIR200B minor: chr1 1071496 1071536 1 chr1 …
elly
  • 317
  • 1
  • 2
  • 11