Iterating across a filtered list

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Tue Mar 13 16:53:22 EDT 2007


Paul Rubin a écrit :
> "Drew" <olsonas at gmail.com> writes:
> 
>>You're exactly on the mark. I guess I was just wondering if your first
>>example (that is, breaking the if statement away from the iteration)
>>was preferred rather than initially filtering and then iterating.
> 
> 
> I think the multiple statement version is more in Python tradition.

I don't know if I qualify as a Python traditionalist, but I'm using 
Python since the 1.5.2 days, and I usually favor list comps or generator 
expressions over old-style loops when it comes to this kind of operations.

> Python is historically an imperative, procedural language with some OO
> features.

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).

>  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)])


> and they have
> some annoying characteristics, like the way they mutate when you touch
> them. 

While sequences are iterables, all iterables are not sequences. Know 
what you use, and you'll be fine.

> 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 ?



More information about the Python-list mailing list