How do you verify that the type of all elements in a list or a tuple are the same and of a certain type?
for example:
(1, 2, 3) # test for all int = True (1, 3, 'a') # test for all int = False
The most straightforward way to get the number of elements in a list is to use the Python built-in function len() . As the name function suggests, len() returns the length of the list, regardless of the types of elements in it.
Method #1 : Using type() This inbuilt function can be used as shorthand to perform this task. It checks for the type of variable and can be employed to check tuple as well.
When it is required to check if two list of tuples are identical, the '==' operator is used. The '==' operator checks to see if two iterables are equal or not. A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
all(isinstance(n, int) for n in lst)
Demo:
In [3]: lst = (1,2,3) In [4]: all(isinstance(n, int) for n in lst) Out[4]: True In [5]: lst = (1,2,'3') In [6]: all(isinstance(n, int) for n in lst) Out[6]: False
Instead of isinstance(n, int)
you could also use type(n) is int
all(isinstance(i, int) for i in your_list))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With