I almost always prefer to read nested loops and conditionals than list comprehensions.
I find the syntax of list comprehensions ugly and inscrutable.
I find the syntax of list comprehensions ugly and inscrutable.
This example…:
a = …
vs = [
v(x)
for b in a.f()
for x in b
if x and c1(x)
and not c2(x)
]
…becomes: a = …
def each_v():
for b in a.f():
for x in b:
if not c1(x): # comment
continue
if c2(x): # comment
continue
if x:
yield v(x)
vs = set(each_v())
Line orienting each conditional makes commenting much easier. The collection used for vs is clear. The formatting is less susceptible to being churned up by black. You get to give the thing a name, which helps.This is basically selling point for comprehensions. You can't add complexity to them so any comprehension you see fits a few common loop patterns you can grok immediately.
If you see an actual for loop in python it means "pay attention something odd is probably going on."