default value in a list
Peter Otten
__peter__ at web.de
Sat Jan 22 04:23:35 EST 2005
Peter Otten wrote:
> 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)
Also nice, IMHO, is allowing individual defaults for different positions in
the tuple:
>>> def expand(items, defaults):
... if len(items) >= len(defaults):
... return items[:len(defaults)]
... return items + defaults[len(items):]
...
>>> expand((1, 2, 3), (10, 20, 30, 40))
(1, 2, 3, 40)
>>> expand((1, 2, 3), (10, 20))
(1, 2)
Peter
More information about the Python-list
mailing list