Python Tutorial - Master Python Programming For Beginners from Scratch

  • Home
  • Getting Started
  • Basics
  • OOP
  • Advanced Python
  • Tkinter
Home » Python Basics » How to Filter List Elements in Python

How to Filter List Elements in Python

Summary: in this tutorial, you’ll learn how to filter list elements by using the built-in Python filter() function.

Introduction to Python filter() function

Sometimes, you need to iterate over elements of a list and select some of them based on specified criteria.

Suppose that you have the following list of scores:

scores = [70, 60, 80, 90, 50]
Code language: Python (python)

To get all elements from the scores list where each element is greater than or equal to 70, you use the following code:

scores = [70, 60, 80, 90, 50] filtered = [] for score in scores: if score >= 70: filtered.append(score) print(filtered)
Code language: Python (python)

How it works.

  • First, define an empty list (filtered) that will hold the elements from the scores list.
  • Second, iterate over the elements of the scores list. If the element is greater than or equal to 70, add it to the filtered list.
  • Third, show the filtered list to the screen.

Python has a built-in function called filter() that allows you to filter a list (or a tuple) in a more beautiful way.

The following shows the syntax of the filter() function:

filter(fn, list)
Code language: Python (python)

The filter() function iterates over the elements of the list and applies the fn() function to each element. It returns an iterator for the elements where the fn() returns True.

In fact, you can pass any iterable to the second argument of the filter() function, not just a list.

The following shows how to use the filter() function to return a list of scores where each score is greater than or equal to 70:

scores = [70, 60, 80, 90, 50] filtered = filter(lambda score: score >= 70, scores) print(list(filtered))
Code language: Python (python)

Output:

[70, 80, 90]
Code language: Python (python)

Since the filter() function returns an iterator, you can use a for loop to iterate over it. Or you can use the list() function to convert the iterator to a list.

Using the Python filter() function to filter a list of tuples example

Suppose you have the following list of tuples:

countries = [ ['China', 1394015977], ['United States', 329877505], ['India', 1326093247], ['Indonesia', 267026366], ['Bangladesh', 162650853], ['Pakistan', 233500636], ['Nigeria', 214028302], ['Brazil', 21171597], ['Russia', 141722205], ['Mexico', 128649565] ]
Code language: Python (python)

Each element in a list is a tuple that contains the country name and population.

To get all the countries whose populations are greater than 300 million, you can use the filter() function as follows:

countries = [ ['China', 1394015977], ['United States', 329877505], ['India', 1326093247], ['Indonesia', 267026366], ['Bangladesh', 162650853], ['Pakistan', 233500636], ['Nigeria', 214028302], ['Brazil', 21171597], ['Russia', 141722205], ['Mexico', 128649565] ] populated = filter(lambda c: c[1] > 300000000, countries) print(list(populated))
Code language: Python (python)

Output:

[['China', 1394015977], ['India', 1326093247], ['United States', 329877505]]
Code language: Python (python)

Summary

  • Use the Python filter() function to filter a list (or a tuple).
  • Was this tutorial helpful ?
  • YesNo
Previous How to Transform List Elements with Python map() Function
Next How to Use the Python Reduce() function to Reduce a List into a Single Value

Getting Started

  • What is Python
  • Install Python
  • Setup VS Code for Python
  • Develop Python Hello World Program

Python Fundamentals

  • Python Syntax
  • Variables
  • Strings
  • Numbers
  • Boolean
  • Constants
  • Comments
  • Type Conversion

Control Flow

  • if…else
  • Ternary Operator
  • for Loop
  • while Loop
  • break
  • continue
  • pass

Functions

  • Python Functions
  • Default Parameters
  • Keyword Arguments
  • Recursive Functions
  • Lambda Expressions
  • Function Docstrings

Python List

  • List
  • Tuple
  • Sorting a List in Place: sort()
  • Sorting a List: sorted()
  • Slicing a List: [::]
  • Unpacking a List
  • Iterating over a List: for loop
  • Finding Index of an Element: index()
  • Iterables
  • Transform List Elements: map()
  • Filtering List Elements: filter()
  • Reducing List Elements: reduce()
  • List Comprehensions

Python Dictionary

  • Dictionary
  • Dictionary Comprehension

Python Set

  • Set
  • Set Comprehension
  • Union of Sets
  • Intersection of Sets
  • Difference between Sets
  • Symmetric Difference of Sets
  • Subset
  • Superset
  • Disjoint Sets

Exception Handling

  • try…except
  • try…except…finally
  • try…except…else

Python Loop with Else Clause

  • for…else
  • while…else
  • do…while Emulation

More on Functions

  • Unpacking Tuples
  • The *args Parameters
  • The **kwargs Parameters
  • Partial Functions

Modules

  • Modules
  • Module Search Path
  • Python __name__
  • Packages

File I/O

  • Reading a Text File
  • Writing to a Text File
  • Creating a Text File
  • Checking If a File Exists
  • Reading from a CSV File
  • Writing to a CSV File

Managing Third-party Packages

  • Python Package Index (PyPI) & PIP
  • Python Virtual Environments
  • Install pipenv on Windows
  • Using pipenv Tool

About pythontutorial.net

Pythontutorial.net helps you master Python programming from scratch fast.

Site Links

  • Home
  • Contact
  • About
  • Privacy Policy

Recent Python Tutorials

  • Tkinter StringVar
  • Tkinter PhotoImage
  • Tkinter OptionMenu
  • Tkinter ScrolledText
  • How to Change the Appearances of Widgets Dynamically Using Ttk Style map() Method

Python References

  • Python String Methods
  • Python MySQL
  • Python PostgreSQL
  • Python Oracle
  • Python SQLite

Copyright © 2021 · by pythontutorial.net. All rights reserved. Log in