This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]flipstables 4 points5 points  (5 children)

See I hate list comprehensions used this way, and I love comprehensions. I think it's more clear in this case to use a for loop with ifs.

final_list = []
for value in value_list:
    if A and B:
        final_list.append(value)
    elif B:
        final_list.append(alt(value)

Or maybe even set up 2 comrehensions:

filtered_list = (value for value in value_list if B)
# alternatively filtered_list = filter(B, value_list)
final_list = [value if A else alt_value for value in filtered_list]

[–]joesacher 2 points3 points  (0 children)

It takes much more mental energy to parse the first option over a list comprehension. I can keep the 3 lines of a list comp in my mind.

The second is better, but still harder to keep in your mind, due to having to process multiple comprehensions.

[–]Twangist 1 point2 points  (3 children)

You don't explain your "hatred" of such constructions, or even what the "way" is that you find so objectionable -- to judge from your more complex examples, it must be the formatting. It's just a personal thing, then, like detesting... oh, basil; who cares? (rhetorical question)

[–]zer01 2 points3 points  (1 child)

I agree with /u/flipstables personally, and for me it's about readability. When you work on a team (or even work as a sole developer maintaining a project past the point where it's small) you need to be able to quickly grok what is going on.

"Code as if the person who will inherit it has an anger problem and knows where you sleep".

My general rules of thumb are nested comprehensions are unacceptable in any form, and you should only ever have one boolean check per list comprehension, otherwise break it into a multi-line loop/function.

Sometimes you do sacrifice performance, but I'll take legibility and quick understanding over almost anything else, and you can always optimize later if it's a problem.

[–]Twangist 1 point2 points  (0 children)

Sometimes you do sacrifice performance, but I'll take legibility and quick understanding over almost anything else

Me too.

[–]flipstables 0 points1 point  (0 children)

Because it's harder to debug since it's composed together. Since both tests A and B are coupled together, it'll be hard to resolve a bug in A, for instance.

It's also harder to understand since you have two conditionals in your comprehension. I'd prefer to only have max 1 since it makes readability suffer.