Check If All Elements of a List Are of the Same Type

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

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

Check if all elements in a list are identical

Use itertools.groupby (see the itertools recipes):

from itertools import groupby

def all_equal(iterable):
g = groupby(iterable)
return next(g, True) and not next(g, False)

or without groupby:

def all_equal(iterator):
iterator = iter(iterator)
try:
first = next(iterator)
except StopIteration:
return True
return all(first == x for x in iterator)

There are a number of alternative one-liners you might consider:

  1. Converting the input to a set and checking that it only has one or zero (in case the input is empty) items

    def all_equal2(iterator):
    return len(set(iterator)) <= 1
  2. Comparing against the input list without the first item

    def all_equal3(lst):
    return lst[:-1] == lst[1:]
  3. Counting how many times the first item appears in the list

    def all_equal_ivo(lst):
    return not lst or lst.count(lst[0]) == len(lst)
  4. Comparing against a list of the first element repeated

    def all_equal_6502(lst):
    return not lst or [lst[0]]*len(lst) == lst

But they have some downsides, namely:

  1. all_equal and all_equal2 can use any iterators, but the others must take a sequence input, typically concrete containers like a list or tuple.
  2. all_equal and all_equal3 stop as soon as a difference is found (what is called "short circuit"), whereas all the alternatives require iterating over the entire list, even if you can tell that the answer is False just by looking at the first two elements.
  3. In all_equal2 the content must be hashable. A list of lists will raise a TypeError for example.
  4. all_equal2 (in the worst case) and all_equal_6502 create a copy of the list, meaning you need to use double the memory.

On Python 3.9, using perfplot, we get these timings (lower Runtime [s] is better):

for a list with a difference in the first two elements, groupby is fastestfor a list with no differences, count(l[0]) is fastest

How to check if list is a list of integers

Try:

all(isinstance(n, int) for n in a)  # False for your example

python: Check if all the elements in the list are only numbers

You can use the type function in conjunction with an all to gather the results.

l1 = [1, 2, 3, 4, 5, 6]
l2 = ["abc", "xyz", "pqr"]

print(all(type(e) in (int, float) for e in l1))
print(all(type(e) in (int, float) for e in l2))

Results in:

True
False

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

You can use set like this

len(set(mylist)) == 1

Explanation

sets store only unique items in them. So, we try and convert the list to a set. After the conversion, if the set has more than one element in it, it means that not all the elements of the list are the same.

Note: If the list has unhashable items (like lists, custom classes etc), the set method cannot be used. But we can use the first method suggested by @falsetru,

all(x == mylist[0] for x in mylist)

Advantages:

  1. It even works with unhashable types

  2. It doesn't create another temporary object in memory.

  3. It short circuits after the first failure. If the first and the second elements don't match, it returns False immediately, whereas in the set approach all the elements have to be compared. So, if the list is huge, you should prefer the all approach.

  4. It works even when the list is actually empty. If there are no elements in the iterable, all will return True. But the empty list will create an empty set for which the length will be 0.

Python: determine if all items of a list are the same item

def all_same(items):
return all(x == items[0] for x in items)

Example:

>>> def all_same(items):
... return all(x == items[0] for x in items)
...
>>> property_list = ["one", "one", "one"]
>>> all_same(property_list)
True
>>> property_list = ["one", "one", "two"]
>>> all_same(property_list)
False
>>> all_same([])
True

check if every element in tuple are same type

Use isinstance:

def auto(*tup):
return all(isinstance(i, type(tup[0])) for i in tup)

Or:

def auto(*tup):
return len(set(map(type, tup))) == 1

Example:

print(auto('red', "aa", "hgbnj"))

Output:

True

Example 2:

print(auto('red', 42, {1,2,3}))

Output:

False

How to check to make sure all items in a list are of a certain type

I think you are making it a little too complex. You can just use all():

a = [1,2,3,4,5]
assert all(isinstance(i, int) for i in a)

a = [1,2,3,4,5.5]
assert all(isinstance(i, int) for i in a)
# AssertionError


Related Topics



Leave a reply



Submit