Python – Filter List based on Data type

Python – Filter List items based on the Data type

To filter a list of items based on the data type of the items in Python, you can use List comprehension and isinstance() built-in function.

In this tutorial, you will learn how to filter a list of items based on the data type of items, with examples.

You may refer Python – Filter List tutorial, to get an idea of how to filter a list.

1. Filter only strings from the List in Python

In this example, we take a list my_list which contains items of data types: string, integer, and float. We have to filter only string items from this list.

We shall use List comprehension with the if condition, where the condition is the call to isinstance() function that checks if the item is the instance of str.

Python Program

my_list = ["Apple", 25, 100, "Fig", "Peach", 3.14, 1.20]

filtered_list = [x for x in my_list if isinstance(x, str)]
print(f"Filtered list : {filtered_list}")
Run Code Copy

Output

Filtered list : ['Apple', 'Fig', 'Peach']

Only the string items made it to the filtered list.

You may refer Python – Filter List tutorial, to get an idea of how to filter a list.

2. Filter only integers from the List in Python

In this example, we shall filter the integers in the list, in the same as that in the previous example.

Python Program

my_list = ["Apple", 25, 100, "Fig", "Peach", 3.14, 1.20]

filtered_list = [x for x in my_list if isinstance(x, int)]
print(f"Filtered list : {filtered_list}")
Run Code Copy

Output

Filtered list : [25, 100]

Only the string items made it to the filtered list.

Summary

In this tutorial of Python Lists, we have seen how to filter a list based on data type in Python, with examples.

Related Tutorials

Code copied to clipboard successfully 👍