indexed() generator

Jonathan Hogg jonathan at onegoodidea.com
Fri Jan 25 19:39:57 EST 2002


On 25/1/2002 22:21, in article slrna53mjq.1il.quinn at hork.ugcs.caltech.edu,
"Quinn Dunkan" <quinn at hork.ugcs.caltech.edu> wrote:

> Also note that mxTools has indices(x) which is like tuple(range(len(x)) and
> irange(x) which is like tuple(zip(indices(x), x)).  Of course now that we have
> generators they could use those, but I like the mxTools functions and think
> they'd be just fine except for huge sequences in low memory situations.

Generators aren't just useful for conserving memory, but also for "lazy"
evaluation, e.g.:

    for i, command in indexed(file):
        if command == 'quit\n':
            break
        else:
            process_command( i, command )

[Not a very good example]

If indexed is a generator, then the iterator it returns will incrementally
fetch lines from 'file' as required. When it gets the quit command it will
stop reading. If indexed builds the structure first, then it will consume
all input, or hang if the input is from the terminal.

Jonathan




More information about the Python-list mailing list