C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Result: The filter() built-in does not return another list. It returns an iterator. We can use the list() function to create a new list.
ListPython program that uses filter
numbers = [10, 20, 0, 0, 30, 40, -10]
# Filter out numbers equal to or less than zero.
result = list(filter(lambda n: n > 0, numbers))
print(result)
Output
[10, 20, 30, 40]
Lambda: The lambda receives each value in the range and names it "x." If it is evenly divisible by 2, it returns true.
RangeSo: The lambda filters out all numbers that are not evenly divisible by 2 (all odd numbers). We are left with even numbers.
Python program that uses filter with range
# Use a range with filter.
# ... Return true in lambda if number is even.
# Even numbers are all evenly divisible by 2.
# We then print all even numbers in the range with filtering.
for value in filter(lambda x: x % 2 == 0, range(0, 10)):
print("EVEN NUMBER IN RANGE:", value);
Output
EVEN NUMBER IN RANGE: 0
EVEN NUMBER IN RANGE: 2
EVEN NUMBER IN RANGE: 4
EVEN NUMBER IN RANGE: 6
EVEN NUMBER IN RANGE: 8