Check if a value occurs multiple times in a list in Python

avatar

Borislav Hadzhiev

Last updated: Jun 17, 2022

banner

Photo from Unsplash

Check if a value occurs multiple times in a list in Python #

Use the list.count() method to check if a value occurs multiple times in a list, e.g. if my_list.count(my_str) > 1:. The list.count() method will return an integer greater than 1 if the value occurs multiple times in the list.

main.py
my_str = 'apple' my_list = ['apple', 'avocado', 'tomato', 'apple'] if my_list.count(my_str) > 1: # 👇️ this runs print('The value exists multiple times in the list') else: print('The value does NOT exist multiple times in the list') print(my_list.count(my_str)) # 👉️ 2

We used the list.count() method to check if a value exists multiple times in a list.

The list.count() method takes a value and returns the number of times the provided value appears in the list.
main.py
my_str = 'apple' my_list = ['apple', 'avocado', 'tomato', 'apple'] print(my_list.count(my_str)) # 👉️ 2

If the list.count() method returns an integer greater than 1, then the value exists multiple times in the list.

If you need to check if the value exists multiple times in the list, ignoring case, convert both the list items and the value to lowercase.

main.py
my_str = 'APPLE' my_list = ['ApPLE', 'avocado', 'tomato', 'APPle'] if [item.lower() for item in my_list].count(my_str.lower()) > 1: # 👇️ this runs print('The value exists multiple times in the list') else: print('The value does NOT exist multiple times in the list')

We used a list comprehension to iterate over the list and convert each string to lowercase.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

The last step is to convert the string we are checking for to lowercase and use the list.count() method.

Both the list items and the string have to be converted to lowercase or uppercase to perform a case-insensitive comparison.

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.