Iterating across a filtered list
bruno.42.desthuilliers at wtf.websiteburo.oops.com
Wed Mar 14 10:23:03 CET 2007
Paul Rubin a écrit :
> Bruno Desthuilliers <bdesth.quelquechose at free.quelquepart.fr> writes:
>> Python has had functions as first class objects and
>> (quite-limited-but) anonymous functions, map(), filter() and reduce()
>> as builtin funcs at least since 1.5.2 (quite some years ago).
> True, though no iterators so you couldn't easily use those functions
> on lazily-evaluated streams like you can now.
Obviously. But what I meant is that Python may not be *so* "historically
FWIW, I first learned FP concepts with Python.
>>> Iterators like that are a new Python feature
>> List comps are not that new (2.0 or 2.1 ?):
>> print "\n".join([contact for name, contact in contacts.items() \
>> if search.match(name)])
> Well you could do it that way but it allocates the entire filtered
> list in memory.
Of course. But then nothing prevents you from using a genexp instead of
the list comp - same final result, and the syntax is quite close:
print "\n".join(contact for name, contact in contacts.items() \
So the fact that genexps are still a bit "new" is not a problem here
IMHO - this programming style is not new in Python.
>>> It's usually safest to create and consume them in the same
>>> place, e.g. creating some sequence and passing it through map, filter, etc.
>> Safest ? Why so ?
> Just that things can get confusing if you're consuming the iterator in
> more than one place.
Indeed. But that's not what we have here. And FWIW, in programming, lots
of things tends to be confusing at first.
More information about the Python-list