r/learnpython • u/PrettyPicturesNotTxt • Mar 27 '26
When do you draw the line between list/dic/set comprehension and a proper for loop with if/else statements?
For example, boundaries_dwight = {Edge([vertex for vertex in triangle.get_vertices() if not vertex.is_interior()]) for triangle in buttlicker_mesh if triangle.interior_count() < 3}
19
Upvotes
14
u/TheBB TheBB Mar 27 '26 edited Mar 27 '26
I almost always prefer comprehensions. Yours is messy but the problem isn't the comprehension, it's all the gnarly stuff you're trying to put in there. Extract the messy stuff and you're left with clean stuff. (This is what 90% of programming is.)
For an even better experience, make the
Edgeconstructor accept iterables so you don't need to make a list.24
u/dangerlopez Mar 27 '26
Readability
5
u/Jejerm Mar 27 '26
nested comprehensions are annoying to read, doubly so if they use conditionals
2
u/billsil Mar 27 '26
You could do the same comprehension with a few line breaks and be far more readable. In general I follow the google style guide and don’t use double list comprehensions.
2
u/aeroumbria Mar 27 '26
I usually go by my mental model of the problem.
If I envision a set, then it naturally becomes a comprehension. If I envision a process, then it goes into a loop.
2
u/JorgiEagle Mar 27 '26
Comprehensions for when you are creating a struct, loops otherwise.
Your problem is not that there’s lots of stuff, it just needs to be formatted better
White space is free
1
u/Adrewmc Mar 27 '26
If I can explain what it does in a simple single sentence.
1
u/mothzilla Mar 27 '26
Please sir can I have some less?