Check if a list contains only strings in Python

avatar

Borislav Hadzhiev

Last updated: Aug 12, 2022

banner

Photo from Unsplash

Check if a list contains only strings in Python #

Use the all() function to check if a list contains only strings, e.g. if all(isinstance(item, str) for item in my_list):. The all() function will return True if the list contains only strings and False otherwise.

main.py
my_list = ['one', 'two', 'three'] if all(isinstance(item, str) for item in my_list): # 👇️ this runs print('The list contains only strings') else: print('The list does NOT contain only strings') # 👇️ True print(all(isinstance(item, str) for item in my_list))

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 a string.

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('apple', str)) # 👉️ True print(isinstance(True, str)) # 👉️ False print(isinstance(100, str)) # 👉️ 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 = ['one', 'two', 'three'] if all(isinstance(item, str) for item in my_list): # 👇️ this runs print('The list contains only strings') else: print('The list does NOT contain only strings')

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

You can use a list comprehension if you need to filter out any non-string values from the list.
main.py
my_list = ['one', 100, 'two', 200, 'three'] only_strings = [item for item in my_list if isinstance(item, str)] print(only_strings) # 👉️ ['one', 'two', 'three']

The list comprehension iterates over the list and filters out any non-string 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, str) for item in my_list): # 👇️ this runs print('The list contains only strings') else: print('The list does NOT contain only strings') # 👇️ True print(all(isinstance(item, str) 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, str) for item in my_list): print('The list contains only strings') else: # 👇️ this runs print('The list does NOT contain only strings')

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.