extract elements of n char from a list

Alex Martelli aleax at aleax.it
Fri Jul 26 08:09:45 EDT 2002


Shagshag13 wrote:

> 
> "Shagshag13" <shagshag13 at yahoo.fr> a écrit dans le message de news:
> ahrchl$v4n9l$1 at ID-146704.news.dfncis.de...
>> hello,
>>
>> i want to efficiently extract elements of n char from a list :
>>
>> n = 2
>> l = ['this', 'is', 'an', 'example']
>> nl = []
>> for i in l:
>>     if len(i) == n:
>>         nl.append(i)
>>
>> nl = ['is', 'an']
>>
>> but i think that some clever guru could use a map() / reduce() or
>> something like that to speed up the process (which is what i
> really need...)
> 
> well, i think that i could use :
> 
> nl = [e for e in l if len(e) ==n]
> 
> but is it efficient ? are they more efficient ways ? and when is it good
> pythoner technique to use list comprehensions ?

It's good Python technique to use list comprehensions when they're
clear, concise, and readable (like here).

It's even better Python technique to worry about efficiency LATER.
"The root of all evil in programming is premature optimization" (Knuth).

It's the best Python technique of all to learn to MEASURE rather
than having to ASK.  Set up a little benchmark script and use it.
THEN you can ask here if the results aren't convincing to you (it's
quite possible to get things wrong).  Tim Peters' introduction
to the Algorithms chapter of "Python Cookbook" (the printed edition
that O'Reilly just launched) is invaluable in showing you exactly
how to perform such little benchmarks for accuracy and solidity.


Alex




More information about the Python-list mailing list