You are currently viewing Filter Elements from Python List

The filter() function in Python is used to filter the elements from the list. Let’s discuss this filter() method by providing different parameters like lambda expressions, and custom functions. List comprehension and for loop can also be utilized to filter the elements in the list. For all three scenarios, we will see different examples by considering different data type elements.

Advertisements

1. Quick Examples of Filtering Elements in List

Following are quick examples of how to filter elements in the list.


# Quick Examples 

# Consider the list of integers
marks=[89,100,23,10,0,67,90]
print("Actual List: ",marks)

# Using filter() with lambda expression
print("Greater than 100: ",list(filter(lambda i: i > 100, marks)))

# Function that return the elements that are greater than 100.
def filter1(i):
    return i > 50
# Using filter() with user defined function
print("Greater than 50: ",list(filter(filter1, marks)))

# Using List comprehension
print("Greater than 50: ",[i for i in marks if i > 50])

# Using for loop to filter
filtered=[]
for i in marks:
    if (i > 50):
        filtered.append(i)
print("Greater than 50: ",filtered)

2. Use filter() to Filter List in Python

The filter() is a built-in function in Python that is used to filter the elements from the iterable object like list, set e.t.c. This function will directly filter the elements in a list by taking the condition as a parameter. We can specify the conditions using lambda expressions/custom functions etc.

filter() takes two parameters, condition as the first parameter and list name as the second parameter.

2.1 filter() Syntax

Let’s see how to specify condition/s inside list comprehension.


# Using filter() with lambda expression
print(list(filter(lambda i: condition, mylist1)))

# Using filter() with custom function
list(filter(function_name, mylist1))

Here, mylist1 is the input list from which you wanted to filter the elements.

2.2 filter() Parameters

  • Condition – It will take condition as the first parameter, the condition can be a custom function/in-built function or lambda expression
  • List – The input list you wanted to filter the elements from.

2.3 Examples

Example 1: Let’s have some integers in a list and filter all elements that are

  1. Filter elements that are greater than 100 : The condition is element > 100
  2. Filter elements that are greater than 100 : The condition is element < 100

# Consider the list of integers
scores=[100,200,300,400,500]
print("Actual List: ",scores)

# Using filter() with lambda expression
print("Greater than 100: ",list(filter(lambda i: i > 100, scores)))
print("Less than 100: ",list(filter(lambda i: i < 100, scores)))

Yields below output.

python filter elements list

There are 4 elements that are greater than 100 and no element is less than 100.

Example 2: Let’s have some strings in a list and filter all elements.

  1. Filter list that endswith – ‘o’
  2. Filter list that startswith – ‘a’.

# Consider the list of strings
fruits=["apple","grape","orange","mango"]
print("Actual List: ",fruits)

# Using filter() with lambda expression
print("Elements that ends with o: ",list(filter(lambda i: i.endswith('o'), fruits)))
print("Elements that starts with a: ",list(filter(lambda i: i.startswith('a'), fruits)))

# Output:
# Actual List:  ['apple', 'grape', 'orange', 'mango']
# Elements that ends with o:  ['mango']
# Elements that starts with a:  ['apple']

Here, ‘mango‘ ends with ‘o‘ and ‘apple‘ starts with ‘a‘.

Example 3: Let’s create two user-defined functions such that the first function will return the integers greater than 100 and less than 100. Pass these function names to the filter() function as the first parameter and the list name as the second parameter.


# Consider the list of integers
scores=[100,200,300,400,500]
print("Actual List: ",scores)

# Function that return the elements that are greater than 100.
def filter1(i):
    return i > 100

# Function that return the elements that are less than 100.
def filter2(i):
    return i < 100

# Using filter() with user defined function
print("Greater than 100: ",list(filter(filter1, scores)))
print("Less than 100: ",list(filter(filter2, scores)))

# Output:
# Actual List:  [100, 200, 300, 400, 500]
# Greater than 100:  [200, 300, 400, 500]
# Less than 100:  []

Here, the first function name is filter1, which will return the integers greater than 100. There are 4 integers and the second function name is filter2, which will return the integers less than 100. There is no integer less than 100. So empty list is returned.

3. Using List comprehension to Filter

We will iterate all elements and specify some conditions in for loop using if statements within List comprehension to filter elements in Python. If the condition is satisfied, the elements are collected in a List comprehension.

3.1 List comprehension Syntax

Let’s see how to specify condition/s inside list comprehension.


# Syntax
[iterator for iterator  in mylist1 if condition/s]

3.2 Examples

Example 1: Let’s have some integers in a list and filter all elements that are greater than 50 and store them in the filtered list.


# Consider the list of integers
marks=[89,100,23,10,0,67,90]
print("Actual List: ",marks)

# Using List comprehension
print("Greater than 50: ",[i for i in marks if i > 50])

# Output:
# Actual List:  [89, 100, 23, 10, 0, 67, 90]
# Greater than 50:  [89, 100, 67, 90]

Here, we used > (greater than) operator inside the condition. There are only 4 elements that are greater than 50.

Example 2: Let’s have some strings in a list and filter all strings that start with ‘a’ and another example that ends with ‘o’.


# Consider the list of strings
fruits=["apple","grape","orange","mango"]
print("Actual List: ",fruits)

# Using List comprehension
print("Elements that start with a: ",[i for i in fruits if i.startswith('a')])
print("Elements that end with o: ",[i for i in fruits if i.endswith('o')])

# Output:
# Actual List:  ['apple', 'grape', 'orange', 'mango']
# Elements that start with a:  ['apple']
# Elements that end with o:  ['mango']

Here, ‘apple‘ starts with ‘a’ and ‘mango‘ ends with ‘o’ hence, these values are returned.

Example 3: Let’s have some strings in a list and filter all strings that starts with ‘a’ and ends with ‘e’


# Consider the list of strings
fruits=["apple","grape","orange","mango"]
print("Actual List: ",fruits)

# Using List comprehension
print("Elements that start with a: ",
    [i for i in fruits if (i.startswith('a') and i.endswith('e'))])

# Output:
# Actual List:  ['apple', 'grape', 'orange', 'mango']
# Elements that start with a:  ['apple']

Here, ‘apple‘ is the only string in the list that start with ‘a’ and end with ‘e’.

4. Filter List Using for loop

Using for loop we will iterate all elements and specify some conditions inside this loop using if statements to filter lists in Python. If the condition is satisfied, the elements are collected in a list through append() method.

4.1 for loop Syntax

Let’s see how to specify condition/s inside for loop.


# Syntax
filtered=[]
for iterator in mylist1:
    if (iterator condition/s):
        filtered.append(iterator )

4.2 Examples

Example 1: Let’s have some integers in a list and filter all elements that are greater than 50 and store them in the filtered list.


# Consider the list of integers
marks=[89,100,23,10,0,67,90]
print("Actual List: ",marks)

# Using for loop to filter
filtered=[]
for i in marks:
    if (i > 50):
        filtered.append(i)
print("Greater than 50: ",filtered)

# Output:
# Actual List:  [89, 100, 23, 10, 0, 67, 90]
# Greater than 50:  [89, 100, 67, 90]

Here, we used > (greater than) operator inside the condition. There are only 4 elements that are greater than 50.

Example 2: Let’s have some strings in a list and filter all strings that end with ‘e’.


# Consider the list of strings
fruits=["apple","grape","orange","mango"]
print("Actual List: ",fruits)

# Using for loop to filter
filtered=[]
for i in fruits:
    if (i.endswith('e')):
        filtered.append(i)
print("Elements that end with e: ",filtered)

# Output:
# Actual List:  ['apple', 'grape', 'orange', 'mango']
# Elements that end with e:  ['apple', 'grape', 'orange']

Here, we specified the condition using the endswith() method. It is used to return string/s ends with a particular character or substring. Out of 4 strings, this example returns 3 strings that ends with ‘e’.

Conclusion

In this article, you have learned how to filter elements from the list in Python. We have seen three different ways to filter elements from a list using filter() method, List comprehension, and for loop.