[Tutor] Amazed

Kent Johnson kent37 at tds.net
Sat Nov 13 18:26:53 CET 2004

I share your feelings about list comprehensions - I like the 
conciseness, and they seem to fit better with how I think, but using one 
purely for the side effects seems like abuse.

Here are a couple of different ways to do what you have below, assuming 
that myset is a sets.Set (or set builtin from Python 2.4):

myset.update( [ x for x in thingToIterate if x ] )

Set.update() takes any iterable as an argument, not just another set.

In Python 2.4 you can use a generator expression to avoid creating the 
intermediate list at all. A generator expression is like a list 
comprehension but its value is an iterator instead of a list:

myset.update(x for x in thingToIterate if x)


You can do something similar in Python 2.3 using itertools.ifilter:

import itertools
myset.update(itertools.ifilter(None, thingToIterate))


Bill Mill wrote:
> Jacob,
> 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:
>         myset.add(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.

More information about the Tutor mailing list