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

Sometimes, while working with Python, we can have a problem in which we need to test if all the elements of argument are of same type or not. This can have application in many domains such as data Science and day-day programming. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop + isinstance()
The combination of above functionalities can be used to perform this task. In this, we test for type using isinstance() and check for all elements if they match same type as of 1st element.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Test if all elements in list are of same type
# using loop + isinstance()
  
# Initializing lists
test_list = [5, 6, 2, 5, 7, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Test if all elements in list are of same type
# using loop + isinstance()
res = True
for ele in test_list:
    if not isinstance(ele, type(test_list[0])):
        res = False 
        break
  
# printing result 
print ("Do all elements have same type : " + str(res))

chevron_right


Output :

The original list is : [5, 6, 2, 5, 7, 9]
Do all elements have same type : True

 

Method #2 : Using all() + isinstance()
This is yet another way to perform this task. In this, we instead of iterating perform the task in one line using all and instance().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Test if all elements in list are of same type
# using all() + isinstance()
  
# Initializing lists
test_list = [5, 6, 2, 5, 7, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Test if all elements in list are of same type
# using all() + isinstance()
res = all(isinstance(sub, type(test_list[0])) for sub in test_list[1:])
  
# printing result 
print ("Do all elements have same type : " + str(res))

chevron_right


Output :

The original list is : [5, 6, 2, 5, 7, 9]
Do all elements have same type : True



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.