4 ms·
I almost always prefer to read nested loops and conditionals than list comprehensions. I find the syntax of list comprehensions ugly and inscrutable.
by spicyusername 4y ago
I almost always prefer to read nested loops and conditionals than list comprehensions.
I find the syntax of list comprehensions ugly and inscrutable.
- xvedejas 4y agoAdditionally I find that it's easier to add complexity to the loops; once you want to start doing nontrivial things in a list comprehension, you often need to rewrite it into a loop first anyway.
- Spivak 4y ago> It's easier to add complexity to the loops 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."
- gorgoiler 4y agoAnother effective technique for making readable, maintainable code is to break the list comprehension out into a generator (as a closure): 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.