Python List Filtering (Methods Explained with Examples)

Sharing is Caring

Filtering items means extracting the desired items from a number of items. The list consists of a number of items. In Python, you must go through a list item by item, apply a condition to each one, and store the items that meet the criteria.

Python List Filtering (Methods Explained with Examples)

Ways to Filter a List in Python

There are different ways to filter a list in python such as :

  1. For Loop Approach
  2. List Comprehension
  3. Built in filter() method

For Loop Approach

Using a for loop is the most straightforward and most user-friendly method of filtering a list. A few key points are listed below:

  • A for loop iterates over each item in an index.
  • It determines whether an element meets a requirement.
  • It inserts the element into the outcome based on the condition.

Let us explain it with an example. Let’s suppose, we want to filter marks more than 80.

marks = [34, 33, 72, 80, 88] student_marks = [] for mark in marks:     if mark >= 80:         student_marks.append(mark)         print(student_marks)

Output

[80, 88]

List Comprehension Approach

List comprehension, in essence, is a shortcut for iterating through a list with a single line of code. It has the following syntax:

[element for element in elements if condition]

Let we explain with an example to filter student marks using a comprehension method.

marks = [34, 33, 72, 80, 88] student_marks = [mark for mark in marks if mark >= 80] print(student_marks)  

Output

[80 , 88]

List Filtering Using Filter() Method

Python’s filter() function’s syntax is as follows:

        filterfunc, elements

A few key points need to be considered.

  • For each item in a list called elements, the filter() process employs a function called func.
  • An element must meet the criterion of the filtering function. If not, it will be removed from the results page.
  • A filter entity with the filtered components is returned by the filter() function. Use the list() function to turn this filter entity into a list.

Let us explain with an example. Let us filter a list of marks greater than or equal to 80 from the pool of list marks. First, we will implement a filtering function that will check the marks.

def marks_check(mark):
    return mark >= 80
marks = [4, 23, 32, 12, 88]
student_marks = filter(marks_check, marks)
print(list(student_marks))
The output will be:
[88]

Also Read: Reinforcement Learning Applications and Working

Python List Filter Map

When a function is applied to each item of an iterable, the map function in Python acts as an iterator to produce a result (tuple, lists, etc.). You use it when you want to transform each iterable element using a single transformation function. In Python, the map receives the iterable and the function as parameters.

Its syntax is as follows:

map(function_to_apply, list_of_inputs)

Let us explain with an example.

rectangle_areas = [8.563, 4.578, 4.0, 6.81, 2.04, 3.50]
result_area = list(map(round, rectangle_areas, range(1, 4)))
print(result_area)

Range restriction to get numbers between 1-4

The output will be:
[2.0, 3.50, 4.0]

So we can say that, Filter() first requires the function to return boolean values (true or false), and then passes each element in the iterable through the function, “filter” those that are false and returning the result of all the elements having passed through the function. Map() goes through every element in the iterable through a function and returns the result of all the elements having passed through the function.

  • Just one iterable is needed, unlike map().
  • To yield a boolean type, the func parameter is necessary. If not, the filter just returns the iterable that was provided to it. Additionally, since only one iterable is necessary, func can implicitly only accept one argument.
  • The filter runs every item in the iterable through the func and only returns items that evaluate to true. The word “filter” in the name, after all, says it all.

List Comprehension

When you wish to make a new list based on the contents of an existing collection, list comprehension offers a more concise syntax.

E.g You wish to create a new list of fruits from an existing list that only includes animals whose names contain the letter “a.”

Without List Comprehension
You must create a for statement with a conditional check inside in the absence of list comprehension:
animals = [“axe”, “buffalo”, “hen”, “cock”, “duck”]
newwlist = []
for y in animals:
if “a” in y:
newwlist.append(y)
print(newwlist)

The output will be:

[‘axe’, ‘buffalo’]

The following code filters the animals which contain “a” in spells.

With List Comprehension
With just one line of code, you can accomplish all of that using list comprehension:
animals = [“axe”, “buffalo”, “hen”, “cock”, “duck”]
newwlist = [y for y in animals if “a” in y]
print(newwlist)

Conclusion

We can conclude that multiple items can be stored in a single variable using lists. To filter the data elements from the list, there are different methods such as we can use built-in function filter(), list comprehension, and loop structures. All methods are explained with examples.

FAQ

How to filter a python list?

We can use the built-in function filter() function, using list comprehension and loop structure.

Leave a Comment