Open In App

Python - Test if all elements in list are of same type

Last Updated : 18 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

When working with lists in Python, there are times when we need to ensure that all the elements in the list are of the same type or not. This is particularly useful in tasks like data analysis where uniformity is required for calculations. In this article, we will check several methods to perform this check.

Using all() and type()

This method uses the all() function combined with type() to iterate through the list and ensure all elements match the type of the first element.

Python
a = [1, 2, 3, 4, 5]

# Check if all elements are of the same type
b = all(type(x) == type(a[0]) for x in a)

print(b)

Output
True

Let's see some more methods on how to test if all elements in list are of the same type.

Using set and type()

This method creates a set of the types of the elements in the list. If all elements are of the same type then the set will have only one unique type.

Example:

Python
a = [1, 2, 3, 4, 5]

# Check if all elements are of the same type
b = len(set(type(x) for x in a)) == 1

print(b)

Output
Same type: True

Explanation:

  • type(lst[0]): Gets the type of the first element in the list.
  • all(): Ensures that the type of every element matches the first element.

Using List Comprehension and isinstance()

This method checks if all elements are instances of a specific type using isinstance() and List Comprehension.

Example:

Python
a = [1, 2, 3, 4, 5]

# Check if all elements are of the same type

b = len(set(type(x) for x in a)) == 1
print(b)

Output
Same type: True

Explanation:

  • set(type(x) for x in lst): Creates a set of unique types in the list.
  • len() == 1: Ensures there’s only one unique type.

Using map() and set

This method applies type() to all elements using map() and creates a set to find unique types, set() and len() ensures there’s only one unique type.

Example:

Python
a = [1, 2, 3, 4, 5]

# Check if all elements are of the same type
is_same_type = len(set(map(type, a))) == 1

print("Same type:", is_same_type)

Output
Same type: True

Explanation:

  • Here, we use map() to apply the type() function to each element of the list identifying their types.
  • A set is used to collect unique types and its length is checked. If the length is 1, all elements have the same type.

Next Article
Practice Tags :

Similar Reads