convert loop to list comprehension

Simon Forman rogue_pedro at yahoo.com
Sat Sep 9 03:17:04 EDT 2006


bvdp at xplornet.com wrote:
<snip>
> 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:
        res.append(expression1)


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)]

becomes:

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

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

R = range(10)

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

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:
            res2.append(m)

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:
            res3.append(m)

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.

HTH,
~Simon




More information about the Python-list mailing list