How To Check The Type Of Elements In List Python

In this tutorial, we will learn how to check the type of elements in a list, using Python. Checking the types of elements in a list can be useful, especially when working with data from different sources, validating, or filtering it. Python has a built-in function called isinstance() that can be used for checking the type of elements in a list.

Step 1: Create a sample list

First, create a sample list that has elements of different data types. The list can have integers, strings, dictionaries, etc.

Step 2: Check the type of elements using isinstance()

To check the type of element, we will use the built-in function isinstance(object, classinfo). This function checks if the given object is an instance of the specified class or a subclass thereof. If the object is an instance of any of the classes specified in the classinfo tuple, the function will return True, otherwise, it will return False.

Here’s a simple example:

True

Now let’s check what type of elements exists in our mixed_list:

1 is an integer
banana is a string
2.5 is a float
{'key': 'value'} is a dictionary
True is a boolean
(1, 1) is a tuple

Step 3: Filter a list based on the element type

In this step, let’s try to filter the mixed_list, and create a new list that only contains integers:

[1, 1]

In this case, the new list contains two elements – 1 and 1. The second element (True) was considered as an integer because in Python, True is considered an instance of the int class (1), and False is considered (0).

Full Code

1 is an integer
banana is a string
2.5 is a float
{'key': 'value'} is a dictionary
True is a boolean
(1, 1) is a tuple
[1, 1]

Conclusion

In this tutorial, we learned how to use the isinstance() built-in function in Python to check the type of elements in a list. We also learned how to filter a list based on the type of elements present in the list. This can be helpful while working with lists that have elements of different data types, ensuring better data integrity and flexibility in code.