Python Filter List
To filter a list, we use filter () method function. The filter () will test every element true or not in the sequence.
Syntax:
Filter(function, sequence)
Parameters:
- Function: Function that check and verifies if each number of a sequence true or not.
- Sequence: sequence has to filter numbers from the list, sets or tuples of any iterator.
- Returns: Returns already filtered numbers from an iterator.
Examples
- Example program for filtering vowels and sequence:
deffun(variable):
alpha =['u', 'o', 'i', 'e', 'a']
if(variable inalpha):
returnTrue
else:
returnFalse
sequence =['z', 'a', 'e', 'm', 'k', 'x', 'v', 'r']
// using filter function
Print('filtered elements:')
form infiltered:
print(m)
Output:
Filtered elements:
a
e
- Example program for odd and even numbers:
sequence=[6,7,8,9,0,5]
// odd elements of the list
res =filter(lambdax: x %2!=0, seq)
print(list(res))
// even elements of the list
res =filter(lambdax: x %2==0, seq)
print(list(res))
Output:
[5, 7, 9]
[0, 6, 8]
Approaches
For filtering list, we have three approaches:
- A for loop approach
- A list comprehension
- filter () method function.
A For Loop Approach
- A for loop will be repeated until its condition fails.
- A for loop goes through every number of a list.
- Based upon the condition numbers are added.
Example:
ages = [15,18,20,10,30]
young_ages = []
for age in ages:
if age >= 18:
young_ages.append(age)
print(young_ages)
Output:
[18, 20, 30]
List Comprehension Approach
In short, list comprehension is a shorthand for looping through a list with one line of code. It follows this syntax:
[number for number in numbers if condition]
Example:
ages = [15, 18, 20, 10, 30]
young_ages = [age for age in ages if age >= 18]
print(young_ages)
Output:
[18, 20, 30]
Filter () Function
The filter () function returns a filter object with the filtered elements. You can convert this filter object into a list using the list() function.
Syntax:
Filter (function, numbers)
Example:
Filtering function that tests ages.
def age_test(age):
return age >= 18
// passing age_test () function
ages = [15, 18, 20, 10, 30]
young_ages = filter(age_test, ages)
print(list(young_ages))
Output:
[18, 20, 30]