[Python-ideas] Add 'interleave' function to itertools?

Joshua Landau joshua at landau.ws
Thu Aug 8 00:27:18 CEST 2013


On 7 August 2013 22:00, Andrew Barnert <abarnert at yahoo.com> wrote:
> On Aug 7, 2013, at 13:02, Serhiy Storchaka <storchaka at gmail.com> wrote:
>
>> 07.08.13 22:19, Vito De Tullio написав(ла):
>>> 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?
>>
>> chain.from_iterable(zip(*iterables))
>
> Yet another reason why chain.from_iterable should be more discoverable. The operation is obviously just flattening/chaining a zip, and the only reason that isn't the obvious code for many people is that they don't know how to flatten.

I agree. I don't think we can get chain.from_iterable renamed to
something better easily¹, but I'm still hopeful that someone will
update the implementation for http://www.python.org/dev/peps/pep-0448/
for me, and that solves it nicely².

¹ At least it wasn't easy last time we tried
² chain.from_iterable(x) == (*i for i in x)


More information about the Python-ideas mailing list