Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unpack tuple of length n to m<n variables [duplicate]

In Python 3 I can do the following (see also PEP3132 on Extended Iterable Unpacking):

a, *b = (1, 2, 3) # a = 1; b = (2, 3) 

What can I do to achieve the same similarly elegant in Python 2.x?


I know that I could use single element access and slicing operations, but I wonder if there is a more pythonic way. My code so far:

a, b = (1, 2, 3)[0], (1, 2, 3)[1:] # a = 1; b = (2, 3) 
like image 864
moooeeeep Avatar asked Apr 24 '12 14:04

moooeeeep


People also ask

Can you unpack a tuple?

In python tuples can be unpacked using a function in function tuple is passed and in function values are unpacked into normal variable.

How do I unpack a tuple in a for loop?

Unpack a Tuple in a for Loop in Python The number of variables on the left side or before the equals sign should equal the length of the tuple or the list. For example, if a tuple has 5 elements, then the code to unpack it would be as follows. We can use the same syntax to unpack values within a for loop.

What do you mean by packing and unpacking in reference to a tuple?

Tuple packing refers to assigning multiple values into a tuple. Tuple unpacking refers to assigning a tuple into multiple variables.


2 Answers

I found out that the related PEP3132 gives some examples for Python 2.x as well:

Many algorithms require splitting a sequence in a "first, rest" pair:

first, rest = seq[0], seq[1:] 

[...]

Also, if the right-hand value is not a list, but an iterable, it has to be converted to a list before being able to do slicing; to avoid creating this temporary list, one has to resort to

it = iter(seq) first = it.next() rest = list(it) 

Other approaches given in the answers to this question:

Function Argument List Unpacking Approach

requires an extra function definition/call:

def unpack(first, *rest):    return first, rest first, rest = unpack( *seq ) 

I wonder why it is implemented in unpacking function argument lists but not for normal tuple unpacking.

Generator Approach

Credits. Also requires a custom function implementation. Is a little more flexible concerning the number of first variables.

def unpack_nfirst(seq, nfirst):   it = iter(seq)   for x in xrange(nfirst):     yield next(it, None)   yield tuple(it) first, rest = unpack_nfirst(seq, 1) 

The most pythonic would probably be the ones mentioned in the PEP above, I guess?

like image 115
moooeeeep Avatar answered Oct 14 '22 16:10

moooeeeep


I may be wrong but as far as I know

a, *b = (1, 2, 3) 

is just syntactic sugar for slicing and indexing tuples. I find it useful but not very explicit.

like image 32
Félix Cantournet Avatar answered Oct 14 '22 14:10

Félix Cantournet