Idiom for default values when unpacking a tuple
Steven Bethard
steven.bethard at gmail.com
Wed Nov 17 22:34:42 EST 2004
Carlos Ribeiro wrote:
> How about having a iterator function that is guaranteed to always
> return a fixed number of elements, regardless of the size of the
> sequence? I've checked it, and it does not exist in itertools.
> Something like this (simple-minded, just a proof of concept, and
> highly optimizable in at least a hundred different ways :-):
>
> def iterfixed(seq, times, defaultitem=None):
> for i in range(times):
> if i < len(seq):
> yield seq[i]
> else:
> yield defaultitem
Well, it doesn't quite exist in itertools, but it's there with just a
simple composition:
>>> def iterfixed(seq, times, defaultitem=None):
... return it.islice(it.chain(iter(seq), it.repeat(defaultitem)), times)
...
>>> tuple(iterfixed((1,2,3,4), 3))
(1, 2, 3)
>>> tuple(iterfixed((1,2,3,4), 6))
(1, 2, 3, 4, None, None)
>>> a,b,c = iterfixed((1,2,3,4), 3)
>>> a,b,c
(1, 2, 3)
>>> a,b,c,d,e,f = iterfixed((1,2,3,4), 6)
>>> a,b,c,d,e,f
(1, 2, 3, 4, None, None)
> The only catch is that, if you have only one parameter, then all you
> will get is the generator itself. But that's a corner case, and not
> the intended use anyway.
Not exactly sure what you mean here. If you only have one item in your
unpack tuple, I believe things still work, e.g.:
>>> a, = iterfixed((1,2,3,4), 1)
>>> a
1
But I'm probably just misunderstanding your statement...
Steve
More information about the Python-list
mailing list