|
| 1 | +--- |
| 2 | +id: filter-function |
| 3 | +title: Filter Function in Python |
| 4 | +sidebar_label: Filter Function |
| 5 | +--- |
| 6 | + |
| 7 | +## Definition |
| 8 | + |
| 9 | +The filter function is a built-in Python function used for constructing an iterator from elements of an iterable for which a function returns true. |
| 10 | + |
| 11 | +**Syntax**: |
| 12 | + |
| 13 | + ```python |
| 14 | +filter(function, iterable) |
| 15 | +``` |
| 16 | + |
| 17 | +**Parameters**: |
| 18 | + |
| 19 | +- **function:** A function that tests if each element of an iterable returns True or False. |
| 20 | +- **iterable:** An iterable like sets, lists, tuples, etc., whose elements are to be filtered. |
| 21 | +- **Returns:** An iterator that is already filtered. |
| 22 | + |
| 23 | +## Basic Usage |
| 24 | + |
| 25 | +**Example 1: Filtering a List of Numbers**: |
| 26 | + |
| 27 | +```python |
| 28 | +# Define a function that returns True for even numbers |
| 29 | +def is_even(n): |
| 30 | + return n % 2 == 0 |
| 31 | + |
| 32 | +numbers = [1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
| 33 | +even_numbers = filter(is_even, numbers) |
| 34 | + |
| 35 | +# Convert the filter object to a list |
| 36 | +print(list(even_numbers)) # Output: [2, 4, 6, 8, 10] |
| 37 | +``` |
| 38 | + |
| 39 | +**Example 2: Filtering with a Lambda Function**: |
| 40 | + |
| 41 | +```python |
| 42 | +numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
| 43 | +odd_numbers = filter(lambda x: x % 2 != 0, numbers) |
| 44 | + |
| 45 | +print(list(odd_numbers)) # Output: [1, 3, 5, 7, 9] |
| 46 | +``` |
| 47 | + |
| 48 | +**Example 3: Filtering Strings**: |
| 49 | + |
| 50 | +```python |
| 51 | +words = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape" , "python"] |
| 52 | +long_words = filter(lambda word: len(word) > 5, words) |
| 53 | + |
| 54 | +print(list(long_words)) # Output: ['banana', 'cherry', 'elderberry', 'python'] |
| 55 | +``` |
| 56 | + |
| 57 | +## Advanced Usage |
| 58 | + |
| 59 | +**Example 4: Filtering Objects with Attributes**: |
| 60 | + |
| 61 | +```python |
| 62 | +class Person: |
| 63 | + def __init__(self, name, age): |
| 64 | + self.name = name |
| 65 | + self.age = age |
| 66 | + |
| 67 | +people = [ |
| 68 | + Person("Alice", 30), |
| 69 | + Person("Bob", 15), |
| 70 | + Person("Charlie", 25), |
| 71 | + Person("David", 35) |
| 72 | +] |
| 73 | + |
| 74 | +adults = filter(lambda person: person.age >= 18, people) |
| 75 | +adult_names = map(lambda person: person.name, adults) |
| 76 | + |
| 77 | +print(list(adult_names)) # Output: ['Alice', 'Charlie', 'David'] |
| 78 | +``` |
| 79 | + |
| 80 | +**Example 5: Using None as the Function**: |
| 81 | + |
| 82 | +```python |
| 83 | +numbers = [0, 1, 2, 3, 0, 4, 0, 5] |
| 84 | +non_zero_numbers = filter(None, numbers) |
| 85 | + |
| 86 | +print(list(non_zero_numbers)) # Output: [1, 2, 3, 4, 5] |
| 87 | +``` |
| 88 | + |
| 89 | +**NOTE**: When None is passed as the function, filter removes all items that are false. |
| 90 | + |
| 91 | +## Time Complexity: |
| 92 | +- The time complexity of filter() depends on two factors: |
| 93 | + 1. The time complexity of the filtering function (the one you provide as an argument). |
| 94 | + 2. The size of the iterable being filtered. |
| 95 | +- If the filtering function has a constant time complexity (e.g., $O(1)$), the overall time complexity of filter() is linear ($O(n)$), where ‘n’ is the number of elements in the iterable. |
| 96 | + |
| 97 | +## Space Complexity: |
| 98 | + |
| 99 | +- The space complexity of filter() is also influenced by the filtering function and the size of the iterable. |
| 100 | +- Since filter() returns an iterator, it doesn’t create a new list in memory. Instead, it generates filtered elements on-the-fly as you iterate over it. Therefore, the space complexity is $O(1)$. |
| 101 | + |
| 102 | +## Conclusion: |
| 103 | + |
| 104 | +Python’s filter() allows you to perform filtering operations on iterables. This kind of operation |
| 105 | +consists of applying a Boolean function to the items in an iterable and keeping only those values |
| 106 | +for which the function returns a true result. In general, you can use filter() to process existing |
| 107 | +iterables and produce new iterables containing the values that you currently need.Both versions of |
| 108 | +Python support filter(), but Python 3’s approach is more memory-efficient due to the use of |
| 109 | +iterators. |
0 commit comments