serial iteration over several lists

Jeffrey Froman Jeffrey at Fro.man
Sun Aug 22 11:05:40 EDT 2004


Martin DeMello wrote:

> Thanks - that looks like an excellent starting point. Has there been any
> work done on bidirectional iterators?

You could emulate one by maintaining a counter for the current index into
the imaginary flattened list, and iterating up to that index with each
prev() call and just past it with each next(). This of course requires that
you basically start from the beginning of your nested list each time
though, and I'm not sure if it would be more or less efficient than
indexing into a pre-flattened list in memory.

One more suggestion -- if you use a recursive generator for your iteration,
you can then use it with a list nested to arbitrary depth, something like:

#############################################

def deep_iter(nested_list):
    for x in nested_list:
        if isinstance(x, list):
            for n in deep_iter(x):
                yield n
        else:
            yield x

#############################################


Jeffrey




More information about the Python-list mailing list