VOOZH about

URL: https://www.geeksforgeeks.org/python/python-filter-range-length-tuples/

⇱ Python - Filter Range Length Tuples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python - Filter Range Length Tuples

Last Updated : 12 Jul, 2025

We are given a list of tuples where each tuple contains multiple elements, and our task is to filter out tuples whose lengths do not fall within a specified range. For example, if we have a = [(1, 2), (3, 4, 5), (6,), (7, 8, 9, 10)] and the range (2, 3), we should keep only tuples with 2 or 3 elements, resulting in [(1, 2), (3, 4, 5)]. Let's discuss different methods to do this in Python.

Using List Comprehension

List comprehension provides a concise and efficient way to filter tuples based on their length.


Output
[(1, 2), (3, 4, 5)]

Explanation:

  • This method iterates through a, keeping only tuples within the length range.
  • It is efficient as it processes elements in a single pass.

Let's explore more ways to filter range length tuples.

Using filter() with a Lambda Function

filter() function provides an alternative functional programming approach to filtering tuples.


Output
[(1, 2), (3, 4, 5)]

Explanation:

  • filter(lambda t: min_len <= len(t) <= max_len, a) selects tuples whose lengths are between min_len and max_len.
  • list(filter(...)) converts the filtered result into a list, producing [(1, 2), (3, 4, 5)].

Using for Loop

Using a for loop and append(), we can manually filter tuples while maintaining readability.


Output
[(1, 2), (3, 4, 5)]

Explanation: The loop iterates through a, checking each tuple’s length and adding valid tuples to result.

Using itertools.compress()

The itertools.compress() function filters elements using a boolean selector, making it useful for complex filtering operations.


Output
[(1, 2), (3, 4, 5)]

Explanation:

  • The mask list stores True for tuples within the valid length range.
  • compress() filters a based on the mask, keeping only valid tuples.

Using NumPy for Large Data

NumPy provides an approach for filtering tuples in structured arrays, though it is more useful for large datasets.


Output
[(1, 2) (3, 4, 5)]

Explanation:

  • np.array(..., dtype=object) creates a NumPy array of tuples with different lengths.
  • List comprehension generates a boolean mask, keeping only tuples with lengths between min_len and max_len.
  • a[...] applies the mask, filtering the tuples, resulting in [(1, 2), (3, 4, 5)].
Comment