9-bits
9-bits

Reputation: 10775

Test type of elements python tuple/list

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

Upvotes: 37

Views: 72413

Answers (5)

Mayank Maheshwari
Mayank Maheshwari

Reputation: 303

you can also check type of elements using 'type' function in python like-

>>> all(type(n) == int for n in last) # [1, 2, 2, 34]
True
>>> all(type(n) == str for n in last) # [1, 2, 2, 34]
False

Upvotes: 1

Mario Wanka
Mario Wanka

Reputation: 511

Only to mention the possibility, you can avoid list comprehension with:

all(map(lambda x: isinstance(x, int), your_list))

Upvotes: 0

senderle
senderle

Reputation: 151157

Depending on what you're doing it may be more Pythonic to use duck typing. That way, things that are int-like (floats, etc.) can be passed as well as ints. In this case, you might try converting each item in the tuple to an int, and then catch any exceptions that arise:

>>> def convert_tuple(t, default=(0, 1, 2)):
...     try:
...         return tuple(int(x) for x in t)
...     except ValueError, TypeError:
...         return default
... 

Then you can use it like so:

>>> convert_tuple((1.1, 2.2, 3.3))
(1, 2, 3)
>>> convert_tuple((1.1, 2.2, 'f'))
(0, 1, 2)
>>> convert_tuple((1.1, 2.2, 'f'), default=(8, 9, 10))
(8, 9, 10)

Upvotes: 5

pod2metra
pod2metra

Reputation: 266

all(isinstance(i, int) for i in your_list))

Upvotes: 8

ThiefMaster
ThiefMaster

Reputation: 318748

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

Upvotes: 68

Related Questions