Hacker News new | ask | show | jobs
by dragonwriter 1475 days ago
> What does `filter` do with `None`?

  filter(None, xs)
is equivalent to:

  filter(lambda x: x, xs)
That is, it will return an iterator over the truthy elements of the passed iterable.
1 comments

I suspect the question was rhetorical. The point is, every reader is going to have that question pop into their head and have to look it up. Better to use code that doesn't raise any questions, even if it's a few more characters.
> Better to use code that doesn't raise any questions, even if it's a few more characters.

Certainly, I agree; I would usually use:

  (x for x in xs if x)
Or, if I know more about the kind of falsy values xs actually needs removed, something more explicit like:

  (x for x in xs if x is not None)
Because Python’s multiplicity of falsy values can also be something of a footgun (particularly, when dealing with something a collection of Optionals where the substantive type has a falsy value like 0 or [] included.)

Instead of:

  filter(None, xs)
Which is terse but potentially opaque.

Though it's additional syntax, I kind of wish genexp/list/set comprehensions could use something like “x from” as shorthand for “x for x in”, which would be particularly nice for filtering comprehensions.