A memo when you are worried about the operation of the built-in function filter
I thought that filter is a high-rise function and takes a function as an argument, but apparently it can take None as an argument.
>>> a = [0,1,1.1,'a',None,False]
>>> b = filter(None,a)
>>> list(b)
[1, 1.1, 'a']
As for the operation, it seems that 0, None, False which are False in bool are removed.
>>> b = filter(lambda x:bool(x),a)
>>> list(b)
[1, 1.1, 'a']
Confirmed using help
help(filter)
class filter(object)
| filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
When None comes to the function part, it seems to behave like filter (lambda x: x, list).
When I tried to check it from the source code, it was quite difficult.
Checking the source using inspect cannot be done with the builtin function.
>>> import inspect
>>> inspect.getsource(filter)
...
TypeError: <class 'filter'> is a built-in class
I checked it from Documentation on Github, but the source is not included. That should be it, the built-in functions are written in C. You can check the source code of the filter function as of Python2 with builtin_filter in Mercurial. I wonder if this hasn't changed even after becoming Python3 ...?
Recommended Posts