default value in a list

Peter Otten __peter__ at
Sat Jan 22 03:56:45 EST 2005

Paul McGuire 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?

> I asked a very similar question a few weeks ago, and from the various
> suggestions, I came up with this:
> line = "AAAA:BBB"
> expand = lambda lst,default,minlen : (lst + [default]*minlen)[0:minlen]
> a,b,c = expand( line.split(":"), "", 3 )

Here is an expand() variant that is not restricted to lists but works with
arbitrary iterables:

from itertools import chain, repeat, islice

def expand(iterable, length, default=None):
    return islice(chain(iterable, repeat(default)), length)


More information about the Python-list mailing list