Sergei
Sergei

Reputation: 605

Checking list values

I have a list that must only contain ints, how would i proceed to control every element of the list and return a message if it is not an int?

Could i for instance somehow use isdigit()?

Thanks

Upvotes: 2

Views: 133

Answers (4)

Michał Šrajer
Michał Šrajer

Reputation: 31192

Why don't you use Array in such case?

From docs:

Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained.

Upvotes: 0

Josh Lee
Josh Lee

Reputation: 177875

You can use all and the abstract base class Number:

>>> all(isinstance(x, Number) for x in mylist)

Upvotes: 7

Michał Trybus
Michał Trybus

Reputation: 11804

You can check if all elements of a list are of a particular type:

all(map(lambda x: type(x) == type(0), list))

This will return False iif there is at least one element of list which is not of the same type as 0. You can change the condition to fit your needs, depending on whether you need integers or reals or anything else.

Upvotes: -1

rplnt
rplnt

Reputation: 2409

You can use abstract base class numbers and a simple loop:

from numbers import Number

for item in my_list:
    if not isinstance(item, Number):
        print '{} is not a number'.format(item)

Upvotes: 0

Related Questions