# Python – Extract tuples with elements in Range

PythonServer Side ProgrammingProgramming

When it is required to extract tuples with elements in a given range, the filter and lambda methods are used.

## Example

Below is a demonstration of the same −

my_list = [(13, 15, 17), (25, 56), (13, 21, 19 ), (44, 14)]

print("The list is :")
print(my_list)

beg, end = 13, 22

my_result = list(filter(lambda sub : all(element >= beg and element <= end for element in sub),
my_list))

print("The result is :")
print(my_result)

## Output

The list is :
[(13, 15, 17), (25, 56), (13, 21, 19), (44, 14)]
The result is :
[(13, 15, 17), (13, 21, 19)]

## Explanation

• A list of tuple is defined and is displayed on the console.

• The values for beginning and end are defined and are displayed on the console.

• A lambda method is used along with ‘all’ operator, to check if an element is greater than beginning value, and less than the end value.

• If yes, it is filtered out using ‘filter’ method and converted to a list.

• This result is assigned to a variable

• This is the output that is displayed on the console.

Updated on 08-Sep-2021 08:32:37