How to unpack tuple of length n to m

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?

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)