default value in a list

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Sat Jan 22 14:45:49 EST 2005


Michael Spencer wrote:
> Alex Martelli wrote:
> [explanation and the following code:]
> 
>>  >>> a, b, c = it.islice(
>>  ...               it.chain(
>>  ...                   line.split(':'), 
>>  ...                   it.repeat(some_default),
>>  ...               ), 
>>  ...           3)
>>  ... 
>>  ...           
>>  >>> 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
> 
> Why not put these together and put it in itertools, since the requirement seems 
> to crop up every other week?
> 
>   >>> line = "A:B:C".split(":")
>   ...
>   >>> def ipad(N,iterable, default = None):
>   ...     return it.islice(it.chain(iterable, it.repeat(default)), N)
>   ...
>   >>> a,b,c,d = ipad(4,line)
>   >>> a,b,c,d
> ('A', 'B', 'C', None)

Good idea!

(+1 if this was posted on python-dev!)

Reinhold



More information about the Python-list mailing list