How are you supposed to break up a very long list comprehension?
[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]
I have also seen somewhere that people that dislike using '\' to break up lines, but never understood why. What is the reason behind this?
works fine, so you can pretty much do as you please. I'd personally prefer
The reason why
\
isn't appreciated very much is that it appears at the end of a line, where it either doesn't stand out or needs extra padding, which has to be fixed when line lengths change:In such cases, use parens:
I'm not opposed to:
You don't need
\
in this case. In general, I think people avoid\
because it's slightly ugly, but also can give problems if it's not the very last thing on the line (make sure no whitespace follows it). I think it's much better to use it than not, though, in order to keep your line lengths down.Since
\
isn't necessary in the above case, or for parenthesized expressions, I actually find it fairly rare that I even need to use it.You can also make use of multiple indentations in cases where you're dealing with a list of several data structures.
Notice how it also filters onto another list using an if statement. Dropping the if statement to its own line is useful as well.