convert loop to list comprehension

Simon Forman rogue_pedro at
Sat Sep 9 09:17:04 CEST 2006

bvdp at wrote:
> Thanks for that, Carl. I think that using the loop is probably what
> I'll end up doing. I had no idea that the listcomp thing would be quite
> a complicated as it is appearing. I had it in my mind that I was
> missing some obvious thing which would create a simple solution :)
> Mind you, there are some interesting bits and pieces of code in this
> thread!

List (and generator) comprehensions are not as bad as all that,
although it took me a little while to figure them out too.  ;-)

They are basically normal for loops with optional if statements:

res = [expression1 for var in some_iter if expression2]

is just like:

res = []
for var in some_iter:
    if expression2:

More complex comprehensions can be broken down the same way (like Rob
Williscroft did for his fourth attempt):

res = [i for i, x in enumerate(seq) for _ in xrange(x)]


res = []
for i, x in enumerate(seq):
    for _ in xrange(x):

Doing this can help you puzzle out variables and if statements in
complex list comps, as the following, admittedly contrived, examples

R = range(10)

res = []
for n in R:
    if n % 2:
        for m in range(n):

print res == [m for n in R if n % 2 for m in range(n)]

res2 = []
for n in R:
    for m in range(n):
        if n % 2:

print res2 == [m for n in R for m in range(n) if n % 2]

res3 = []
for n in R:
    for m in range(n):
        if m % 2:

print res3 == [m for n in R for m in range(n) if m % 2]

# The above prints True three times.

Of course, if your loops get much more complicated than this you should
probably "spell them out" anyway.


More information about the Python-list mailing list