Check if all elements in a list are integers in Python

avatar

Borislav Hadzhiev

Last updated: Aug 12, 2022

banner

Photo from Unsplash

Check if all elements in a list are integers in Python #

Use the all() function to check if all elements in a list are integers, e.g. if all(isinstance(item, int) for item in my_list):. The all() function will return True if all of the elements in the list are integers and False otherwise.

main.py
my_list = [3, 5, 8] if all(isinstance(item, int) for item in my_list): # 👇️ this runs print('All of the items in the list are integers') else: print('Not all of the items in the list are integers')

We used a generator expression to iterate over the list.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the current item is an integer.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

main.py
print(isinstance(100, int)) # 👉️ True print(isinstance(3.14, int)) # 👉️ False print(isinstance('hello', int)) # 👉️ False

The all() built-in function takes an iterable as an argument and returns True if all elements in the iterable are truthy (or the iterable is empty).

main.py
my_list = [3, 5, 8] if all(isinstance(item, int) for item in my_list): # 👇️ this runs print('All of the items in the list are integers') else: print('Not all of the items in the list are integers')

If the all() function encounters an item that is not an integer, it will short-circuit returning False.

You can use a list comprehension if you need to filter out any non-integer values from the list.
main.py
my_list = ['one', 3, 'two', 5, 'four', 8] only_ints = [item for item in my_list if isinstance(item, int)] print(only_ints) # 👉️ [3, 5, 8]

The list comprehension iterates over the list and filters out any non-integer values.

Note that the all() function returns True for any condition if the provided iterable is empty.

main.py
my_list = [] if all(isinstance(item, int) for item in my_list): # 👇️ this runs print('All of the items in the list are integers') else: print('Not all of the items in the list are integers') # 👇️ True print(all(isinstance(item, int) for item in my_list))

If you need to handle a scenario where the list is empty, check for its length.

main.py
my_list = [] if len(my_list) > 0 and all(isinstance(item, int) for item in my_list): print('All of the items in the list are integers') else: # 👇️ this runs print('Not all of the items in the list are integers')

We used the boolean and operator, so for the if block to run both conditions have to be met.

The list doesn't have a length greater than 0, so the else block runs.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.