Filter a list of tuples in Python

avatar

Borislav Hadzhiev

Last updated: Jun 29, 2022

banner

Photo from Unsplash

Filter a list of tuples in Python #

To filter a list of tuples in Python:

  1. Use a list comprehension to iterate over the list.
  2. Return a condition from the list comprehension.
  3. The new list will only contain the tuples for which the condition is met.
main.py
# ✅ filter a list of tuples using a list comprehension list_of_tuples = [('Alice', 1), ('Bob', 2), ('Carl', 3), ('Dean', 4)] filtered_list = [tup for tup in list_of_tuples if tup[1] > 2] # 👇️ [('Carl', 3), ('Dean', 4)] print(filtered_list) # ------------------------------------------------------------- # ✅ filter a list of tuples using the `filter()` function filtered_list_2 = list( filter( lambda tup: tup[1] > 2, list_of_tuples ) ) # 👇️ [('Carl', 3), ('Dean', 4)] print(filtered_list_2)

We used a list comprehension to filter a list of tuples.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

On each iteration, we check if the second item (index 1) of the current tuple is greater than 2 and return the result.

The new list only contains the tuples for which the condition returned a truthy value.

Alternatively, you can use the filter() function.

To filter a list of tuples in Python:

  1. Use the filter() function to filter the list.
  2. The filter function returns an iterator containing the results.
  3. Pass the filter object to the list() class to convert it to a list.
main.py
list_of_tuples = [('Alice', 1), ('Bob', 2), ('Carl', 3), ('Dean', 4)] filtered_list_2 = list( filter( lambda tup: tup[1] > 2, list_of_tuples ) ) # 👇️ [('Carl', 3), ('Dean', 4)] print(filtered_list_2)

The filter function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.

The filter function returns a filter object, so we had to pass the filter object to the list() class to convert it to a list.

The lambda function gets called with each tuple in the list, checks if the second item in the tuple is greater than 2 and returns the result.

The final list only contains the tuples for which the condition was satisfied.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.