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

List operation for nested list

I have the following list: list = [(1,info1),(2,info2),(3,info3)...] each info is consisted of a list of tuples info1 = [(a1,b1,c1),(a1',b1',c1'),(a1",b1",c1")...] for each element in list, i want to have the following: otherlist =…
Kristof Pal
  • 966
  • 4
  • 12
  • 28
0
votes
3 answers

Extracting integers from a string of ordered pairs in Python?

This may be super simple to a lot of you, but I can't seem to find much on it. I have an idea for it, but I feel like I'm doing way more than I should. I'm trying to read data from file in the format (x1, x2) (y1, y2). My goal is to code a distance…
Stephen Paul
  • 2,762
  • 2
  • 21
  • 25
0
votes
5 answers

list received is bigger than expected

I am working on nmea processing for gps trackers, where I am processing it as a list of values on this way """ information package…
Carlos
  • 4,299
  • 5
  • 22
  • 34
0
votes
1 answer

Python: loading text with 3 columns of data

I have a text file with 3 columns of data I want to plot. from numpy import * import pylab from mpl_toolkits.mplot3d import Axes3D datalist = loadtxt("datagrid.txt") x, t, u = datalist[:, 0, 0], datalist[0, :, 0], datalist[0, 0, :] fig =…
dustin
  • 4,309
  • 12
  • 57
  • 79
0
votes
3 answers

Convert a split string to a tuple results in "too many values to unpack"

Using split in a for loop results in the mentioned exception. But when taking the elements indpendent from a for loop it works: >>> for k,v in x.split("="): ... print k,v ... Traceback (most recent call last): File "", line 1, in…
WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560
0
votes
2 answers

Python: unpacking into array elements

Why does the behavior of unpacking change when I try to make the destination an array element? >>> def foobar(): return (1,2) >>> a,b = foobar() >>> (a,b) (1, 2) >>> a = b = [0, 0] # Make a and b lists >>> a[0], b[0] = foobar() >>> (a, b) ([2, 0],…
Gordon Bean
  • 4,272
  • 1
  • 32
  • 47
0
votes
2 answers

Unpacking iterable into other iterable?

While reading data from a ASCII file, I find myself doing something like this: (a, b, c1, c2, c3, d, e, f1, f2) = (float(x) for x in line.strip().split()) c = (c1, c2, c3) f = (f1, f2) If I have a determinate number of elements per line (which I…
gerrit
  • 24,025
  • 17
  • 97
  • 170
0
votes
1 answer

How to unpack a tuple while calling an external method in Python?

I call a method of an external library multiple times in my class like this: class MyClass: const_a = "a" const_b = True const_c = 1 def push(self, pushee): with ExternalLibrary.open(self.const_a, self.const_b,…
0
votes
3 answers

Unpacking error in python

I'm making a script and i need to do this: for ip, location, zone, dns in data: But i get this error: ValueError: need more than 3 values to unpack The data is built it this way: def loadfile(): nativeFile = open("Zonechilds.csv","r") …
X3MBoy
  • 203
  • 4
  • 12
0
votes
2 answers

How can I avoid nested tuple unpacking when enumerating zipped lists?

How can I avoid using nested tuple unpacking when enumerating a list of tuples like this? for i, (x, y) in enumerate(zip("1234", "ABCD")): # do stuff
Lauritz V. Thaulow
  • 49,139
  • 12
  • 73
  • 92
0
votes
2 answers

Python how to initialize thread with unknown number of arguments?

I'm having trouble using the starred expressions in combination with fixed argument lists when attempting to create threads. Consider the following code: the_queue = Queue() def do_something(arg1, arg2, queue): # Do some stuff... result =…
Atra Azami
  • 2,215
  • 1
  • 14
  • 12
0
votes
2 answers

How do you take data from Python sort and perform some math on the tuple without messing up the sort order?

I am writing a script to list the 20 largest files in a target directory. Once I have the files, I perform some math on the size to apply the correct human readable sizing information, i.e., Kb, Mb, Gb. This however is getting the sort out of…
Josh
  • 25
  • 4
-1
votes
1 answer

What can I use instead of 'None' so it'll be iterable?

Is there something I can return instead of 'None' so that it's still iterable but empty? Sometimes I want to return two values but sometimes I only want to return one. for distance in range(1, 8): temp_cords = [(origin[0] -…
ThePawn08
  • 13
  • 1
-1
votes
1 answer

Access elements of Python tuple in Matlab

I want to run and access the output of a Python function in Matlab. Please find below function. The python function returns a Python tuple as output in Matlab. Can I access elements of tuple in Matlab? I do not want to export output as .mat file and…
Husnain
  • 243
  • 1
  • 2
  • 5
-1
votes
2 answers

Assign a subset of values from a list returned by an iterable to a variable (Python)

I have an iterable that returns multiple values as a list. In this case, I only care about one of the values in each iteration. As a concrete example: class Triples: def __init__(self): self.x = 0 def __iter__(self): return self def…
wfaulk
  • 1,765
  • 1
  • 17
  • 24