Python – Filter Items of Tuple

To filter items of a Tuple in Python, call filter() builtin function and pass the filtering function and tuple as arguments. The filtering function should take an argument and return True if the item has to be in the result, or False if the item has to be not in the result.

filter() function returns a filter object, which we can convert it to tuple using tuple().

Python filter() builtin function

Examples

1. Filter Even Numbers from Tuple of Integers

In the following program, we take a tuple `x` with integers and filter only even numbers using filter function.

Python Program

```aTuple = (2, 5, 8, 1, 14, 3, 16)
result = filter(lambda x: x % 2 == 0, aTuple)
result = tuple(result)
print(result)```
Try Online

Output

`(2, 8, 14, 16)`

2. Filter Only Integers from a Tuple

Now, let us take a tuple with items of different data types. Using filter() function, we filter only integers.

Python Program

```aTuple = (2, 5, 'Abc', 14, 'Mno', True)
result = filter(lambda x: type(x) == int, aTuple)
result = tuple(result)
print(result)```
Try Online

Output

`(2, 5, 14)`

Conclusion

In this Python Tutorial, we learned how to filter items of a Tuple in Python using filter() function, with examples.