[Tutor] 2 problems in a small script

Kent Johnson kent37 at tds.net
Fri Oct 12 14:35:55 CEST 2007


Dick Moores wrote:
> At 03:41 AM 10/12/2007, Kent Johnson wrote:
>>   finalList = [ word for word in lstA if all(c in astr for c in word) ]
> 
> I'm just not comfortable with list comprehensions yet,

Hmm, too bad. I use list comps and generator expressions constantly.

> but I see that 
> although yours is very succinct, it's clear enough.

Or maybe *because* it is succinct. Most list comps and genexps are 
either applying a function to every element of a list (map):
[ f(x) for x in seq ]

or filtering a list:
[ x for x in seq if f(x) ]

and occasionally both:
[ f(x) for x in seq if g(x) ]

where f and g could be actual functions or simple expressions.

I think the reason I like them so much is because they are succinct, 
high-level, and flow in the same order as my thoughts. For example, the 
requirement "Give me a list of the square of every element of seq" 
translates directly to
[              # Give me a list
x*x            # of the square
for x in seq ] # of every element of seq

and "I need a list of every element in seq that is > 2" becomes
[              # I need a list
x for x in seq # of every element in seq
if x>2 ]       # that is > 2

I have a writeup here:
http://personalpages.tds.net/~kent37/kk/00003.html

Kent


More information about the Tutor mailing list