filter()
A built-in that keeps the items of an iterable for which a function returns a true value.
In more detail
filter(f, items) returns a lazy iterator of the items where f(item) is true. Passing None instead of a function keeps the items that are true in themselves, dropping 0, empty strings and None. Its results are used up after one pass, like map's.
Example
print(list(filter(None, [0, 1, '', 'a']))) # [1, 'a']Related terms
- map() — A built-in that applies a function to every item of one or more iterables and returns a lazy iterator.
- lambda — A small function written inline as an expression, such as lambda x: x * 2, with no name and a single expression as its body.
- truthiness — How Python treats any value as true or false in a condition: zero, empty collections, empty strings and None are false; nearly everything else is true.
Taught in
- Strings Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Class Variables, Instance Variables And __dict__ — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- List Comprehensions, Filtered And Nested — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Lambdas, map() And filter() — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Generators And Iterators — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Comprehensions, Closures And Files Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Twelve Traps, Mostly Objects — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Mock, Review And Exam Day — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep