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

Problem with str.partition() and tuple unpacking

I am using partition in strings and am trying to use tuple unpacking on them but it's returning the error expected 3 got 1. So here's my code. Please explain where I went wrong. a='aca' for a,b,c in a.partition('c'): print(a)
0
votes
2 answers

Confusion with unpacking in python

This is basically a code golf problem I was solving. The statement goes like so: Given N, X and a line with X numbers between 0 and 9. Print all valid numbers between 0 and N inclusive. A number is valid if all of your digits are in line. If the…
duckkkk
  • 51
  • 1
  • 7
0
votes
3 answers

Mapping Software Problem in Python Data Structures Course in SoloLearn

I'm currently working on the Mapping Software problem in the Tuple Unpacking lesson in the Python Data Structures course on SoloLearn. I ran my code in my own IDE and it came out to what I think is correct but the test case in SoloLearn says I'm…
0
votes
2 answers

How do I unpack this nested object?

Inside a function, I want to print, for all function parameters, "parameter_name=value" And I want to get the data from inspect.getfullargspec()[0:4:3], which seems to return a tuple of lists with variable names, and variable values. class…
0
votes
1 answer

Purpose of '*' in front of Python3 function

I saw the code for a ResNet CNN in Python3 and PyTorch here as follows: def resnet_block(input_channels, num_channels, num_residuals, first_block=False): blk = [] for i in range(num_residuals): if i == 0 and not…
Arun
  • 2,222
  • 7
  • 43
  • 78
0
votes
0 answers

Tuple unpacking to new and existing variables in a statically typed language with type inference

Consider a tuple of types integer, float, string: (int, float, string) x = (2, 4.2, "string") Unpacking the values from the tuples can be achieved with type inference or pre defining the types. (int, float, string) (arg1, arg2, arg3) =…
Tom
  • 1,235
  • 9
  • 22
0
votes
2 answers

Unpack list of objects into separate attributes

I have a simple Python class like this: class P(object): def __init__(self, x, y): self.x = x self.y = y I create a list of these objects e.g.: import random list_of_objects = [P(random.random(), random.random()) for i in…
akrylic
  • 53
  • 6
0
votes
3 answers

Unpacking Tuple in Dictionary Value

i have a tuple of suspects those suspects exist in dictionary and in the dictionary i have a tuple value i try to unpacking the values to varibles suspects = ( {'name': 'Anne', 'evidences': ('derringer', 'Caesarea')}, {'name': 'Taotao',…
0
votes
2 answers

Unpacking nested tuples using list comprehension

I have a list: path = [ (5, 5), 'Start', 0, ((5, 4), 'South', 1), ((5, 3), 'South', 1), ((4, 3), 'West', 1), ((4, 2), 'South', 1), ((3, 2), 'West', 1), ((2, 2), 'West', 1), ((2, 1), 'South', 1), ((1, 1),…
0
votes
1 answer

TypeError at /cart/ cannot unpack non-iterable Cart object

I am developing an eCommerce app in Django. I am still developing locally. As I try to access to http://127.0.0.1:8000/cart/ I get the error: TypeError at /cart/ cannot unpack non-iterable Cart object in cart_home cart_obj, new_obj =…
Tms91
  • 3,456
  • 6
  • 40
  • 74
0
votes
1 answer

Python dict unpacking operator not unpacking string in constructor

I am creating a small app using socketio in python on server side and JS on client side. For one of my events, the client emits a character object that was created by the user in the browser to be persisted by the server. On the server side, some…
0
votes
1 answer

Loop through list of tuples and unpack elements of each tuple

I have this list of two-value tuples stake_odds=[(0, 1), (0, 2), (0, 5), (0, 10), (2, 1), (2, 2), **(2, 5)**, (2, 10), (5, 1), (5, 2), (5, 5), (5, 10), (10, 1), (10, 2), (10, 5), (10, 10)] I have the following function where I want to put the tuple…
0
votes
1 answer

Setting kwargs for train_test_split

I have a notebook that iterates over the same model, with increasing features. I'd like to simply fill out the train_test_split() with a dict of the relevant args, rather than filling it out each time. For my Random Forest model, for example, I've…
Yehuda
  • 1,787
  • 2
  • 15
  • 49
0
votes
3 answers

Python ValueError: too many values to unpack For Loop

Hi I have a DF i am trying to send to HTML table. For sample, here is the one and only row I have: mdf = [('2007291533_946908J.70J.908J-06.FPP.FMGN512.rSBDl5kn9o4R4wP7dtmissbinallerrors.log', 'K946', 'nabcs', '027', 'ERROR:…
edo101
  • 629
  • 6
  • 17
0
votes
1 answer

How to control the depth of unpacking of nested arguments and pass them as separate arguments to a Python function?

Say we have an NxM array. From this, I want to unpack the N rows as 1xM arrays and pass them to a Python function as separate arguments. An example scenario would be the SciPy package optimize.curve_fit, which has the rather productivity-killing…
david
  • 201
  • 2
  • 10