In the first examples you gave, you mentioned the lack of readability of the comprehension may not be worth saving a few lines of code.

I wanted to remind readers that another advantage of list comprehensions is they are faster in nearly all circumstances. So readability is only one concern.

I.e.

mikes@ubuntu:~$ time python3 -c "result = []

for i in range(100000000):

if i > 10:

if i < 20:

if i % 2:

result.append(i)"

real 0m5.795s

user 0m5.783s

sys 0m0.000s

mikes@ubuntu:~$ time python3 -c "[i for i in range(100000000) if i > 10 if i < 20 if i % 2]"

real 0m3.576s

user 0m3.565s

sys 0m0.008s

Mike Rightmire
Mike Rightmire

Written by Mike Rightmire

Computational and molecular biologist. Observative speculator. Generally pointless non-stop thinker.

Responses (2)