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

Python idiomatic unpacking assignment or False

If function returns a two value list or tuple on success or False on failure, how can I best unpack the return list into two variables while also checking for False? def get_key_value(): if (cond != True): return False return [val1, val2] #…
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
0
votes
3 answers

Python3 dictionary comprehension with sub-dictionary upacking?

Suppose one has a dictionary, root which consists of key:value pairs, where some values are themselves dictionaries. Can one (and if so, how) unpack these sub dictionaries via dictionary comprehension? e.g. {k: v if type(v) is not dict else **v for…
0
votes
1 answer

Unpacking different numbers of variables

I want to make a function that is flexible with regard to unpacking the number of input variables. More specifically, for example I have the following: def flexi_func(vars): func_var_a, func_var_b, func_var_c, func_var_d = vars #do…
berkelem
  • 2,005
  • 3
  • 18
  • 36
0
votes
1 answer

dict comprehension failure - not enough values to unpack

I want to create a dict from a list of strings: print(l) print(l[0]) # 1st string in list print(l[0].split(',',1)) print(len(l[0].split(',',1))) d = {int(k):v for k,v in l[0].split(',',1)} ['0,[7,2,5,7]',…
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
0
votes
1 answer

Type of Python data type list is either list or tuple depending on usage but why

>>> lst = [[-2, -1], [0, 1, 2]] >>> lst [[-2, -1], [0, 1, 2]] >>> print (*lst) [-2, -1] [0, 1, 2] >>> print (type(lst)) So the type for lst is here is list In the context of a function call - I am not sure why it is still not a…
Utpal Mattoo
  • 890
  • 3
  • 17
  • 41
0
votes
6 answers

Convert dictionary (with a tuple as the values) to a list?

I made a dictionary: sort = { str(4213) : ("STEM Center",0), str(4201) : ("Foundations Lab",1), str(4204) : ("CS Lab",2), str(4218) : ("Workshop Room",3), str(4205) : ("Tiled Room",4), "Out" : ("Outside",5) } How do I…
etess
  • 17
  • 2
0
votes
1 answer

Python syntax for returning both a single unpacked value or multiple packed values from a sequence

this might be a great pythonic heresy, but I'm looking for syntax that replicates the behavior of the code below, without using both the return and the yield clause in the function "sign" (edit this syntax does not in fact produce the below…
0
votes
1 answer

Python to convert tuple to value

I'm trying to retrive number of rows in table with: import postgresql db = postgresql.open(...) res = db.query("select count(1) from testdata") print(res) >>> (10,) How can I print just 10?
CrPbI3yH
  • 13
  • 4
0
votes
0 answers

Convert unicoded list of tuples of a dataframe row to a processiable/iterable format

Here is my code snippet where I am trying to process a column of a pandas dataframe def langprob(lid_set): print lid_set, type(lid_set) return df['ls']= df.apply(lambda row: langprob(row['lid']), axis=1) And I am getting the output as…
kingmakerking
  • 2,017
  • 2
  • 28
  • 44
0
votes
4 answers

How to store same value in two variables while independently changing them both in python?

I am trying to create a recursive function that returns the set of all non-empty subset of [1,2,3,...,n] numbers. Here is my code: def subsets(n): if n == 2: return ([1], [2], [1, 2]) else: previous = subsets(n - 1) …
Zero
  • 53
  • 1
  • 1
  • 5
0
votes
0 answers

List slicing and unpacking

Working on a codefights problem. Got stuck on the solution, or rather, solving the way codefights wanted me too. Here is the solution def listBeautifier(a): res = a[:] while res and res[0] != res[-1]: a, *res, d = res return…
RhythmInk
  • 513
  • 1
  • 4
  • 18
0
votes
2 answers

Not enough values to unpack in chained assignment

I know this isn't the way to assign multiple values in one line, but I'm just trying to understand what the 4th line is doing here: a = input("blah blah") b = input("blah blah blah") c = input("blaaah") A=a,B=b,C=c print(A,B,C) If a,b,c were int or…
Alex Matt
  • 209
  • 1
  • 4
0
votes
1 answer

Explanation on unpacking a list with itertools.product

I cant seem to wrap my head around how unpacking (*) along with itertools.product() is working with the example below. for x in product(["ghi","abc"]): print(x) output: ('ghi',) ('abc',) And using * for x in product(*["ghi","abc"]): …
user1179317
  • 2,693
  • 3
  • 34
  • 62
0
votes
1 answer

Is there a simple pythonic way to increase variables while unpacking a tuple?

I want to do something like: a,b,c,d = 1,2,3,4 a,b,c,d += 2,4,6,8 But this does not work. I know I can increase them individually but I thought there would be a simpler way. The only alternative I came up with was this ugly list…
James
  • 387
  • 1
  • 11
0
votes
2 answers

reduce - 'int' object is not iterable

Let's say I have some data stored as "this is row -1 and column -1 with value", 12345 in a csv file. (It's not actually stored like that, the point is the first value in the csv is a string that contains the necessary coordinates.) I should now…
User1291
  • 7,664
  • 8
  • 51
  • 108