Discussion about this post

User's avatar
Eric Matthes's avatar

This is great! Comprehensions can be confusing at first, but they come up quite often in Python.

One of the few drawbacks of formatters like black and ruff is how they handle comprehensions with conditionals. Here's how I've seen comprehensions formatted sometimes to make them more readable:

[

name

for name in names

if len(name) > 5

]

Both black and ruff collapse this into a single line. You can insert directives to skip reformatting on these lines, but that adds its own kind of clutter. Even if our comprehensions end up reformatted on a single line, knowing they can be broken up like this can help you make sense of them.

If you come across a comprehension you're struggling to make sense of, try writing it with the spacing that Stephen showed in this post, or breaking it up across lines. Even if a formatter undoes your work, your comprehension will remain. :)

Expand full comment
Kwame Osei-Tutu's avatar

Finally! I understand why list comprehensions behave like that

Expand full comment
8 more comments...

No posts