proposal: concatenation of iterators

Mark McEahern marklists at mceahern.com
Mon Aug 12 11:17:03 EDT 2002


> It would sure be useful sometimes to be able to say
> 
>   a = iter((2, 3, 4))
>   b = iter((5, 6, 7))
> 
>   for x in a + b:  # concatenate two iterators
>      print x,
> 
> and get:
> 
>   2 3 4 5 6 7

Short answer:  yield to the magic of generators.

Demo:

#! /usr/bin/env python

from __future__ import generators

a = iter((2, 3, 4))
b = iter((5, 6, 7))

def combo_iter(*args):
    for i in args:
        for x in i:
            yield x

for x in combo_iter(a, b):
    print x,

p.s. yeah, my variable naming leaves much to be desired.
-





More information about the Python-list mailing list