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?
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.
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.
To select multiple items in a list, hold down the Ctrl (PC) or Command (Mac) key. Then click on your desired items to select.
>>> 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
>>>
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