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:
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)) <= 1Comparing against the input list without the first item
def all_equal3(lst):
return lst[:-1] == lst[1:]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)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:
all_equal
andall_equal2
can use any iterators, but the others must take a sequence input, typically concrete containers like a list or tuple.all_equal
andall_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 isFalse
just by looking at the first two elements.- In
all_equal2
the content must be hashable. A list of lists will raise aTypeError
for example. all_equal2
(in the worst case) andall_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):
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:
It even works with unhashable types
It doesn't create another temporary object in memory.
It short circuits after the first failure. If the first and the second elements don't match, it returns
False
immediately, whereas in theset
approach all the elements have to be compared. So, if the list is huge, you should prefer theall
approach.It works even when the list is actually empty. If there are no elements in the iterable,
all
will returnTrue
. But the empty list will create an emptyset
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
Pandas Create New Column with Count from Groupby
How to Get the Nth Element of a Python List or a Default If Not Available
How to Request a Url in Python and Not Follow Redirects
How to Set a Default Parameter Equal to Another Parameter Value
Change the Colors Within Certain Range to Another Color Using Opencv
Naming Conflict with Built-In Function
Number of Days Between 2 Dates, Excluding Weekends
Find Longest Repetitive Sequence in a String
Running a Process in Pythonw with Popen Without a Console
Force Numpy Ndarray to Take Ownership of Its Memory in Cython
How Can Strings Be Concatenated
Plot Pandas Dataframe as Bar and Line on the Same One Chart