Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if every item in a list of type 'int'?

Tags:

python

list

int

Say I have a list of numbers. How would I do to check that every item in the list is an int?
I have searched around, but haven't been able to find anything on this.

for i in myList:
  result=isinstance(i, int)
  if result == False:
    break

would work, but looks very ugly and unpythonic in my opinion.
Is there any better(and more pythonic) way of doing this?

like image 267
vurp0 Avatar asked May 15 '11 16:05

vurp0


People also ask

How do you check if all elements of a list are integers?

A list of integers is defined and is displayed on the console. The 'all' operator is used to check if every element is a digit or not. This is done using the 'isdigit' method. The result of this operation is assigned to a variable.

How do you check a condition for all elements in a list?

Method #1 : Using all() We can use all() , to perform this particular task. In this, we feed the condition and the validation with all the elements is checked by all() internally.

How do you test multiple items in a list?

To select multiple items in a list, hold down the Ctrl (PC) or Command (Mac) key. Then click on your desired items to select.


1 Answers

>>> my_list = [1, 2, 3.25]
>>> all(isinstance(item, int) for item in my_list)
False

>>> other_list = range(3)
>>> all(isinstance(item, int) for item in other_list)
True
>>> 
like image 92
AnalyticsBuilder Avatar answered Sep 23 '22 01:09

AnalyticsBuilder