Filter in Python
Python : Filter
What is Filter in Python? In Python,
filter()
is a built-in function that can be used to filter out items from a sequence based on a given condition. It takes two arguments: a function and a sequence. The function is applied to each element in the sequence, and if the function returns True, that element is included in the result; if it returns False, the element is excluded.
Filter Syntax in Python:
filter(function, sequence)
Filter Parameters in Python:
- function: The function to be applied to each element in the sequence. It takes one argument and returns a Boolean value.
- sequence: The sequence to be filtered.
- Return Value: A filtered iterable object containing only the elements from the original sequence for which the function returned True.
Filter use cases in Python?
Filtering even numbers from a list
# define a list of numbers numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # define a function to filter even numbers def is_even(num): return num % 2 == 0 # use filter to get only even numbers even_numbers = list(filter(is_even, numbers)) # print the result print(even_numbers) # Output: [2, 4, 6, 8, 10]
Filtering strings with length greater than 5
# define a list of strings fruits = ['apple', 'banana', 'kiwi', 'orange', 'pear', 'strawberry'] # define a function to filter strings with length greater than 5 def is_long_string(s): return len(s) > 5 # use filter to get only long strings long_strings = list(filter(is_long_string, fruits)) # print the result print(long_strings) # Output: ['banana', 'orange', 'strawberry']
Filtering a dictionary based on a condition
# define a dictionary of people and their ages ages = {'Alice': 25, 'Bob': 30, 'Charlie': 35, 'David': 40} # define a function to filter people whose age is greater than 30 def is_above_thirty(age): return age > 30 # use filter to get only people above 30 above_thirty = dict(filter(lambda x: is_above_thirty(x[1]), ages.items())) # print the result print(above_thirty) # Output: {'Charlie': 35, 'David': 40}
Previous Article
Next Article
Python Tutorials
- Hello World
- Variables and Types
- Lists
- Tuple
- Basic Operators
- Strings
- Conditions
- Loops
- Functions
- Classes and Objects
- Dictionaries
- Map
- Filter
- Reduce
- Sets
- Decorators
- Generators
- Modules and Packages
- Numpy Arrays
- Pandas Basics
- List Comprehensions
- Lambda functions
- Multiple Function Arguments
- Partial functions
- Regular Expressions
- Exception Handling
- Serialization
- Code Introspection