default value in a list

Alex Martelli aleaxit at
Sat Jan 22 09:40:36 CET 2005

TB <tbolands at> wrote:

> Is there an elegant way to assign to a list from a list of unknown
> size?  For example, how could you do something like:
> >>>  a, b, c = (line.split(':'))
> if line could have less than three fields?

import itertools as it

a, b, c = it.islice(

I find itertools-based solutions to be generally quite elegant. 

This one assumes you want to assign some_default to variables in the LHS
target beyond the length of the RHS list.  If what you want is to repeat
the RHS list over and over instead, this simplifies the first argument
of islice:

a, b, c = it.islice(it.cycle(line.split(':')), 3)

Of course, you can always choose to write your own generator instead of
building it up with itertools.  itertools solutions tend to be faster,
and I think it's good to get familiar with that precious modules, but
without such familiarity many readers may find a specially coded
generator easier to follow.  E.g.:

def pad_with_default(N, iterable, default=None):
    it = iter(iterable)
    for x in it:
        if N<=0: break
        yield x
        N -= 1
    while N>0:
        yield default
        N -= 1

a, b, c = pad_with_default(3, line.split(':'))

The itertools-based solution hinges on a higher level of abstraction,
glueing and tweaking iterators as "atoms"; the innards of a custom coded
generator tend to be programmed at a lower level of abstraction,
reasoning in item-by-item mode.  There are pluses and minuses to each
approach; I think in the long range higher abstraction pays off, so it's
worth the investment to train yourself to use itertools.

In the Python Cookbook new 2nd edition, due out in a couple months,
we've added a whole new chapter about iterators and generators, since
it's such a major subfield in today's Python (as evidenced by the wealth
of recipes submitted to Activestate's online cookbook sites on the
subject).  A couple of recipes have do with multiple unpacking
assignment -- one of them, in particular, is an evil hack which peers
into the caller's bytecode to find out how many items are on the LHS, so
you don't have to pass that '3' explicitly.  I guess that might be
considered "elegant", for suitably contorted meanings of "elegant"...
it's on the site, too, but I don't have the URL at hand.  It's
instructive, anyway, but I wouldn't suggest actually using it in any
kind of production code...


More information about the Python-list mailing list