Multiple Unpacking Assignment in Python when you don't know the sequence length

Posted by doug on Stack Overflow See other posts from Stack Overflow or by doug
Published on 2010-03-28T03:17:54Z Indexed on 2010/03/28 3:23 UTC
Read the original article Hit count: 318

Filed under:

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.

© Stack Overflow or respective owner

Related posts about python