views:

130

answers:

2

The textbook examples of multiple unpacking assignment are something like:

import numpy as NP
M = NP.arange(5)
a, b, c, d, e = M
# so of course, a = 0, b = 1, etc.

M = NP.arange(20).reshape(5, 4)     # numpy 5x4 array
a, b, c, d, e = M
# here, a = M[0,:], b = M[1,:], etc. (ie, a single row of M is assigned each to a through e)

(My Q is not numpy specfic; indeed, i would prefer a pure python solution.)

W/r/t the piece of code i'm looking at now, i see two complications on that straightforward scenario:

  • i usually won't know the shape of M; and

  • i want to unpack a certain number of items (definitely less than all items) and i want to put the remainder into a single container

so back to the 5x4 array above, what i would very much like to be able to do is, for instance, assign the first three rows of M to a, b, and c respectively (exactly as above) and the rest of the rows (i have no idea how many there will be, just some positive integer) to a single container, all_the_rest = [].

I'm not sure if i have explained this clearly; in any event, if i get feedback i'll promptly edit my Question.

+1  A: 

Python 3.x can do this easily:

a, b, *c = someseq

Python 2.x needs a bit more work:

(a, b), c = someseq[:2], someseq[2:]
Ignacio Vazquez-Abrams
Your 2.x solution doesn't work. The stuff you're unpacking doesn't match.
Mike Graham
To fix the 2.x solution, all that's needed is a parenthesis around a and b, so that the number of values to assign matches. i.e. `(a, b), c = someseq[:2], someseq[2:]`
mjv
+4  A: 

Syntax for this is added to Python 3

>>> # Python 3.x only
>>> a, b, *c = range(10)
>>> a
0
>>> b
1
>>> c
[2, 3, 4, 5, 6, 7, 8, 9]

but no similar solution exists in Python 2.

You can of course do

>>> s = range(10)
>>> s
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> (a, b, c), rest = s[0:3], s[3:]
>>> a
0
>>> b
1
>>> c
2
>>> rest
[3, 4, 5, 6, 7, 8, 9]

or other similar solutions.

Mike Graham