Re:WTFPython: Exploring and understanding Python through sur...
by zelphirkalt on Tuesday May 31, 2022 @05:58AM
(#31567708)
What does `filter` do with `None`? Would it not be an error? This seems not so readable, possibly relying on weird behavior of `filter`. If I had to guess, I would say: Maybe filter with `None` will give the empty list or the whole list, because either no list item matches a `None` condition, or all match it, since there is no condition.
But in both cases the usage does not seem to make any sense. So it must be something else. Maybe when the argument is not a lambda, it will compare directly with the given argument? But then we would get only `None`. Nah, still makes no sense.
I am at a loss, what this `filter` call is doing, without trying it out.
[ Parent
| on HN ]
Re:WTFPython: Exploring and understanding Python through sur...
by dragonwriter on Tuesday May 31, 2022 @06:55AM
(#31568080)
> 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.
Re:WTFPython: Exploring and understanding Python through sur...
by quietbritishjim on Tuesday May 31, 2022 @08:34AM
(#31568781)
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.
Re:WTFPython: Exploring and understanding Python through sur...
by dragonwriter on Tuesday May 31, 2022 @01:21PM
(#31572193)
> 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.
Re:WTFPython: Exploring and understanding Python through sur...
by weird-eye-issue on Tuesday May 31, 2022 @06:52AM
(#31568063)
From the docs:
If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
So it just removes false-y values.
Very handy I've used it a ton