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

"Python" How to split a word of n bytes into n words of two bytes?

I've been looking for an answer at my problem, and I can't find anything really similar to my problem. The thing is that I'm dealing with a value coming from a sensor in binary and I cast it into a hex value. Until that point there is no problem,…
0
votes
1 answer

Unpacking iterables in Python3?

Why is this returning in sort_tup_from_list for key, val in tup: ValueError: not enough values to unpack (expected 2, got 1) # list with tuples lst = [("1", "2"), ("3", "4")] # sorting list by tuple val key def sort_tup_from_list(input_list): …
Hrvoje T
  • 3,365
  • 4
  • 28
  • 41
0
votes
2 answers

Unpacking instance variables by making container iterable

I just want to be able to unpack the instance variables of class foo, for example: x = foo("name", "999", "24", "0.222") a, b, c, d = *x a, b, c, d = [*x] I am not sure as to which is the correct method for doing so when implementing my own…
0
votes
1 answer

using multiple values of a key in a for loop

I am trying to modify a script that was using a pair of key:value in a for loop. I have to make changes to so the for loop can take 3 values for the key instead of just 1. Not sure how to go about it. Thanks in advance. I get this error: for…
FutureB
  • 5
  • 4
0
votes
1 answer

Unpacking error when unpacking map object

n, m = map(int, [1, 2]) will got n == 1, m == 2 but: n, m, r = map(int, [1, 2]), defaultdict(list) will raise: ValueError: not enough values to unpack (expected 3, got 2) this time, n is , m is the defaultdict I am very…
Rancho
  • 1,988
  • 2
  • 12
  • 12
0
votes
1 answer

Assigning values to multiple names

I have seen many Python snippets where they write something like this: labels, features = targetFeatureSplit(data) or something like ages_train, ages_test, net_worths_train, net_worths_test = train_test_split(ages, net_worths, test_size=0.1,…
Salma
  • 119
  • 3
  • 15
0
votes
1 answer

Python: "too many values to unpack" when assigning result of str.split()

I have a file like this: a hello b goodbye c submarine I want to save it to a dictionary like this: file = {'a': 'hello', 'b': 'goodbye', 'c': 'submarine'} I tried this: file={} with open("the actual file") as f: for line in…
0
votes
0 answers

Python tuple decomposition with unused elements

I have a for-loop with with a tuple decomposition expression. maybe it's known as tuple unpacking. Example code: for funcname,func in self.GetMethods: # do somthing with func # funcname is unused My code checking tool (I'm testing Landscape.io)…
Paebbels
  • 15,573
  • 13
  • 70
  • 139
0
votes
0 answers

Unpacking tuples to form numpy array

I've got a list of tuples of the form: freq_chan =…
Afzal
  • 189
  • 3
  • 14
0
votes
1 answer

Curious tuple-unpacking

I stumbled around a curious behaviour for tuple unpacking, which i could not explain at first. Now while typing this as a SO question it became clear, but i felt it was of enough general interest to post it nevertheless. def test(rng): a, b, c =…
Don Question
  • 11,227
  • 5
  • 36
  • 54
0
votes
2 answers

Assign fixed number of variables to elements in variable length list

Background: I have a python script to check working hours of employees. Each employee has morning and afternoon shifts, with lunch time in between, and each time they put the finger a new timestamp is recorded. So, depending on the time of each day,…
heltonbiker
  • 26,657
  • 28
  • 137
  • 252
0
votes
1 answer

List of tuples unpacking does not work

I am aware of * operator but this one does not seem to work. I basically want to unpack this list consisting of tuple pairs: sentence_list = [('noun', 'I'), ('verb', 'kill'), ('noun', 'princess')] Consider my class Sentence: class…
user3056783
  • 2,265
  • 1
  • 29
  • 55
0
votes
1 answer

python distribute elements of a list into part of a sql query

In python, I have the following sql query: qry = "insert into golden_table (alpha, beta, week1, week2, week3, clust_list, nGram) values (%s %s %s %s %s %s %s)" Now I wish to do something like: L = ['a', 'b', 'c'] qry % (1, 2, UNPACK(L), "herp",…
CodeKingPlusPlus
  • 15,383
  • 51
  • 135
  • 216
0
votes
1 answer

I'm looking for a neat way to return multiple matrices in python

I'm trying to find a neater way of returning an arbitrary number of NxN matrices. Right now I'm using this function from numpy import matrix, zeros def empty_matrix( dim, num ): """Returns an empty square matrix of type complex and size a.""" …
0
votes
2 answers

Unpacking? strange commas in python

I was looking at some code that returns the second largest element of a list and came across a weird use of commas. Hopefully someone can explain it to me: it is the m1, m2 = x, m1 part of the following code: def second_largest(numbers): m1, m2…
natsuki_2002
  • 24,239
  • 21
  • 46
  • 50