Tom Ritchford
1 min readNov 22, 2023

--

It isn't! You have the syntax wrong, it goes like this:

[i for i in items if i is not None]

(It’s generally better to use single letter variables in comprehensions and generators, and their scope is just one line…)

As to why, this was discussed in great detail on the Python dev mailing list a very long time ago, and it seems there’s pretty well only one way to do it, for various reasons due to parsing and ambiguity (that I didn’t fully internalize, but I was convinced all these smart people had…)

I never found such expressions difficult, but for a while I was confused by doing nested loops like this:

[j for i in list_of_lists for j in i]

But I realized it was again the only way it could work — the outermost loop has to come at the start.

Now we have the walrus operator, we can even do things like this:

[v for i in items if (v := f(i)) is not None]

I would write that in production code, but that’s close to the limit of the complexity I would allow in a single generator or comprehension.

But you can always split them up for basically no cost:

it = (f(i) for i in items)
[v for v in it if v is not None]

--

--

Responses (1)