How To Filter A List In Python

Filtering a list means to find and extract items from a list based upon some condition. In Python, there are different ways to filter out items from a list. This article is about how to filter a list in Python. One way is to use a built-in filter() function or by using a for loop. There’s an even easier way to filter out items using the lambda function and comprehension method. We will discuss all of them one by one in detail.

If you want to learn more about Python Programming, visit Python Tutorials.

METHOD 01: Using Filter function to find specific items from the list

Python provides a built-in function filter() function which can be applied to an iterable such as a list or a dictionary etc. This function can filter out certain specific elements based on the provided condition.

Syntax:      
filter(function, iterable)

function: The function which is applied on all the elements of an iterable
iterable: List, dictionary etc.

studentsAge = [12, 25, 23, 18, 19, 22, 23, 17, 18, 12, 13]

def Func(input):
  if input < 18:
    return False
  else:
    return True


aboveEighteen = filter(Func, studentsAge)
for student in aboveEighteen:
  print(student)
25
23
18
19
22
23
18

There are three functions to filter items which include filter, map and reduce. To learn the difference between them, read this article.

Method 02: Filter a list using the Lambda function

Lambda is an anonymous function which behaves like normal functions arguments but it can evaluate and return only one expression. It can be used in combination with filter() function to find items that meet a certain condition and filter them out.

studentsAge = [12, 25, 23, 18, 19, 22, 23, 17, 18, 12, 13]

aboveEighteen = filter(lambda age: age >= 18, studentsAge)

for student in aboveEighteen:
  print(student)
25
23
18
19
22
23
18

Similarly, consider another example in which we want to extract the countries’ names whose length is less than 5. Now, we can use lambda and filter function to check each element of the list and len() function to check the number of alphabets in the name. In this example, the countries whose length is less than five are filtered out and stored in a separate list.

countries=['pak','us','uae','india','turkey']
count=filter(lambda x: len(x) < 5,countries)
list(count)
Output:
['pak', 'us', 'uae']

Suppose we have a list of items. Our goal is to extract the words which start with specific character. Filter () function can be applied on a list to extract all the items that start with alphabet ‘s’ and store them in a separate list. The following example demonstrates how you can separate the items starting with ‘s’ from the others and create two lists based on the filtered items.

listOfItems= ['sweet','map','carpet', 'scissor','bottle', 'umbrella', 'bag', 'sanitizer']
start_letter = 's'
# using filter() + startswith() + lambda
with_s = list(filter(lambda x: x.startswith(start_letter), listOfItems))
without_s = list(filter(lambda x: not x.startswith(start_letter), listOfItems))
print("The list without prefix s : " + str (without_s))
print("The list with prefix s : " + str (with_s))
The list without prefix s : ['map', 'carpet', 'bottle', 'umbrella', 'bag']
The list with prefix s : ['sweet', 'scissor', 'sanitizer']

METHOD 3: FILTERING ITEMS USING LIST COMPREHENSION

We can also add a conditional expression(if-else) or even for loops in a list comprehensions in order to filter out desired items. The list comprehension simplifies the code and reduce the logic in a single line. The following code checks which of the items in the list ‘stationaryItems’ are present in ‘listOfItems’ and store them in a separate list.

stationaryItems =['pencil', 'eraser', 'ruler']

listOfItems= ['sweet','map','pencil','carpet', 'scissor','bottle', 'umbrella', 'bag', 'eraser' ,'sanitizer', 'sharpener']

itemsFound=[i for i in listOfItems for j in stationaryItems if i== j]
itemsFound

['pencil', 'eraser']

The easiest way to filter data in Python is through list comprehensions. If you have to check only one condition then you can use lambda function along with filter function. But if you have to apply check multiple conditions then you can use method 1. Create a function which takes an element as an argument and evaulate all those conditions on that element. This function is then passed along with the list to be filtered to the filter() function. This page has walked you through the basics of using list comprehensions and lambda functions to filter lists in Python with examples. If you hae any queries, contact us.

Leave a Comment

Your email address will not be published. Required fields are marked *