Check if a string is in a list ignoring case in Python

avatar

Borislav Hadzhiev

Last updated: Jul 13, 2022

banner

Photo from Unsplash

Check if a string is in a list ignoring case in Python #

To check if a string is in a list ignoring case:

  1. Iterate over the list and convert each string to lowercase.
  2. Convert the string to check for to lowercase.
  3. Use the in operator to check if the string is in the list in a case-insensitive manner.
main.py
my_str = 'apple' my_list = ['APPLE', 'BANANA', 'KIWI'] if my_str.lower() in (item.lower() for item in my_list): # 👇️ this runs print('The string is in list') else: print('The string is not in the 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 use the str.lower() method to convert the current string to lowercase.

main.py
my_list = ['APPLE', 'BANANA', 'KIWI'] # 👇️ ['apple', 'banana', 'kiwi'] print(list(item.lower() for item in my_list))

The str.lower method returns a copy of the string with all the cased characters converted to lowercase.

The method doesn't change the original string, it returns a new string. Strings are immutable in Python.

The last step is to convert the string we are checking for to lowercase and use the in operator.

main.py
my_str = 'apple' my_list = ['APPLE', 'BANANA', 'KIWI'] if my_str.lower() in (item.lower() for item in my_list): # 👇️ this runs print('The string is in list') else: print('The string is not in the list')

The in operator tests for membership. For example, x in l evaluates to True if x is a member of l, otherwise it evaluates to False.

Both strings have to either be lowercase or uppercase to perform a case-insensitive comparison.

If your list contains items that are not strings, use the str() class to convert each item to a string before calling the lower() method.

main.py
my_str = 'kiwi' my_list = ['APPLE', 1, 'BANANA', 2, 'KIWI'] if my_str.lower() in (str(item).lower() for item in my_list): # 👇️ this runs print('The string is in list') else: print('The string is not in the list')

The lower() method is specific to strings, so we have to convert each list item to a string before using it.

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.