default value in a list

Michael Spencer mahs at telcopartners.com
Sat Jan 22 20:38:49 CET 2005


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)

Michael




More information about the Python-list mailing list