[Tutor] Amazed

Bill Mill bill.mill at gmail.com
Fri Nov 12 06:40:16 CET 2004


I think it's a readability problem - it's too easy to abuse list
comprehensions to turn a 2 or 3 line for loop into a difficult to
understand one-liner. Today I found myself doing:

[myset.add(x) for x in thingToIterate where x]

instead of:

for x in thingToIterate:
    if x:

which is much more readable, and doesn't eat the memory of creating an
unnecessary list full of 'None'. I immediately fixed my mistake, but
it made me realize how addictive list comprehensions are; they're like
Python crack.

Bill Mill
bill.mill at gmail.com

On Thu, 11 Nov 2004 22:27:18 -0500, Jacob S. <keridee at jayco.net> wrote:
> Wow!
>     I'm amazed that several people are having trouble with list
> comprehensions. I must think in that style or something. I've come up with
> odd uses for them. This one threw me for a while...
> newlist = []
> powers = []
> a = 'x**2+sin(x)+2*x'
> a = a.split("+")
> powers = [newlist.append(x) for x in a if x.count('**') >= 1]
> print powers
> #Code yields
> [None]
>     Since this is embeded deep in sloppy code, it took me a bit to realize
> that I was really wanting newlist.
> So...
> >>> print newlist
> ['x**2']
> Just thought I'd share an odd usage of list comprehensions with you all.
> Jacob Schmidt
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

More information about the Tutor mailing list