Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test type of elements python tuple/list

Tags:

python

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 
like image 224
9-bits Avatar asked Jan 22 '12 19:01

9-bits


People also ask

How do you check the type of an element in a list Python?

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.

How do I know what type of tuple I have?

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.

How do you check if elements of a tuple are same?

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).


2 Answers

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

like image 64
ThiefMaster Avatar answered Sep 18 '22 22:09

ThiefMaster


all(isinstance(i, int) for i in your_list)) 
like image 27
pod2metra Avatar answered Sep 18 '22 22:09

pod2metra