Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if all elements of a list are of the same type

How can I check if the elements of a list are of the same type, without checking individually every element if possible?

For example, I would like to have a function to check that every element of this list is an integer (which is clearly false):

x = [1, 2.5, 'a']  def checkIntegers(x):     # return True if all elements are integers, False otherwise 
like image 204
linello Avatar asked Nov 06 '12 13:11

linello


People also ask

How do you check if all elements in a list are the same type Python?

Method #1 : Using loop + isinstance() In this, we test for type using isinstance() and check for all elements if they match same type as of 1st element.

How do you check if all elements of a list are the same?

You can convert the list to a set. A set cannot have duplicates. So if all the elements in the original list are identical, the set will have just one element. if len(set(input_list)) == 1: # input_list has all identical elements.

How do you check if all elements in a list are the same Java?

allMatch() method. The allMatch() method returns true if all elements of the stream matches with the given predicate. It can be used as follows to check if all elements in a list are the same.


1 Answers

Try using all in conjunction with isinstance:

all(isinstance(x, int) for x in lst) 

You can even check for multiple types with isinstance if that is desireable:

all(isinstance(x, (int, long)) for x in lst) 

Not that this will pick up inherited classes as well. e.g.:

class MyInt(int):      pass  print(isinstance(MyInt('3'),int)) #True 

If you need to restrict yourself to just integers, you could use all(type(x) is int for x in lst). But that is a VERY rare scenario.


A fun function you could write with this is one which would return the type of the first element in a sequence if all the other elements are the same type:

def homogeneous_type(seq):     iseq = iter(seq)     first_type = type(next(iseq))     return first_type if all( (type(x) is first_type) for x in iseq ) else False 

This will work for any arbitrary iterable, but it will consume "iterators" in the process.

Another fun function in the same vein which returns the set of common bases:

import inspect def common_bases(seq):     iseq = iter(seq)     bases = set(inspect.getmro(type(next(iseq))))     for item in iseq:         bases = bases.intersection(inspect.getmro(type(item)))         if not bases:            break     return bases 

like image 97
mgilson Avatar answered Oct 14 '22 17:10

mgilson