How to filter a tuple in Python

avatar

Borislav Hadzhiev

Last updated: Jun 29, 2022

banner

Photo from Unsplash

Filter a tuple in Python #

To filter a tuple in Python:

  1. Use the filter() function to filter the tuple.
  2. The filter function returns an iterator containing the results.
  3. Pass the filter object to the tuple() class to convert it to a tuple.
main.py
# ✅ filter a tuple my_tuple = (1, 3, 5, 7, 9, 12) filtered_tuple = tuple( filter(lambda item: item > 5, my_tuple) ) # 👇️ (7, 9, 12) print(filtered_tuple) # ----------------------------------------------------- # ✅ filter a list of tuples list_of_tuples = [('Alice', 1), ('Bob', 2), ('Carl', 3), ('Delilah', 4)] filtered_list = [tup for tup in list_of_tuples if tup[1] > 2] # 👇️ [('Carl', 3), ('Delilah', 4)] print(filtered_list)

We used the filter() function to filter a tuple.

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 tuple() class to convert it to a tuple.

If you pass None for the function argument, all falsy elements of the iterable are removed.

main.py
my_tuple = (1, 0, '', 3, 5, 0, '') filtered_tuple = tuple( filter(None, my_tuple) ) # 👇️ (1, 3, 5) print(filtered_tuple)

The function filtered out the empty strings and the zeros from the tuple.

All values that are not truthy are considered falsy. The falsy values in Python are:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type
  • empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).

Alternatively, you can use a list comprehension.

To filter a tuple:

  1. Use a list comprehension to iterate over the tuple.
  2. Return a condition from the list comprehension.
  3. Use the tuple() class to convert the list to a tuple.
main.py
my_tuple = (1, 3, 5, 7, 9, 12) filtered_tuple = tuple([item for item in my_tuple if item > 5]) # 👇️ (7, 9, 12) print(filtered_tuple)

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 tuple item is greater than 5 and return the result.

The last step is to use the tuple() class to convert the list to a tuple.

Tuples are very similar to lists, but implement fewer built-in methods and are immutable (cannot be changed).

Since tuples cannot be changed, the only way to filter a tuple is to return a new tuple that contains the necessary elements.

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.