[Python-ideas] Add 'interleave' function to itertools?
MRAB
python at mrabarnett.plus.com
Wed Aug 7 22:12:53 CEST 2013
On 07/08/2013 20:19, Vito De Tullio wrote:
> MRAB wrote:
>
>> def interleave(*iterables):
>> """Return a interleave object whose .__next__() method returns an
>> element from each iterable argument in turn. The .__next__()
>> method continues until the shortest iterable in the argument
>> sequence is exhausted and then it raises StopIteration.
>> """
>>
>> sources = [iter(iterable) for iterable in iterables]
>>
>> try:
>> while True:
>> for iterable in sources:
>> yield next(iterable)
>> except StopIteration:
>> pass
>
> isn't something like
>
> def interleave(*iterables):
> for zipped_iterables in zip(*iterables):
> yield from zipped_iterables
>
> sufficient?
>
> (and the same for interleave_longest / zip_longest)
>
You're probably correct, although there's still the corner case of what
should happen when an iterable is exhausted. For example, what should
list(interleave([0, 2, 4], [1, 3])) return? Should it be [0, 1, 2, 3,
4] or [0, 1, 2, 3]? In other words, if there are 'n' iterables, should
'interleave' always yield a multiple of 'n' items? Should there be a
function for each case?
And are these functions worthy of inclusion in itertools? :-)
More information about the Python-ideas
mailing list