Find the index of string in a list ignoring case in Python

avatar

Borislav Hadzhiev

Last updated: Jul 7, 2022

banner

Photo from Unsplash

Find the index of string in a list ignoring case in Python #

To find the index of a string in a list ignoring case:

  1. Use a list comprehension to convert the strings in the list to lowercase.
  2. Use the list.index() method to get the index of the string in the list.
  3. The index method will return the index of the first occurrence of the string in the list.
main.py
my_str = 'apple' my_list = ['APPLE', 'BANANA', 'KIWI'] idx = [item.lower() for item in my_list].index(my_str.lower()) print(idx) # 👉️ 0

We used a list comprehension to convert the list of strings to lowercase.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.
main.py
my_str = 'apple' my_list = ['APPLE', 'BANANA', 'KIWI'] all_lower = [item.lower() for item in my_list] print(all_lower) # 👉️ ['apple', 'banana', 'kiwi']

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 use the list.index() method to get the index of the string in the list.

main.py
my_str = 'apple' my_list = ['APPLE', 'BANANA', 'KIWI'] idx = [item.lower() for item in my_list].index(my_str.lower()) print(idx) # 👉️ 0

The list.index() method returns the index of the first item whose value is equal to the provided argument.

Make sure to convert the string to lowercase when passing it to the list.index() method.

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

The list.index() method raises a ValueError if there is no such item in the list.

If you need to handle the scenario where the value is not found in the list, use a try/except statement.

main.py
my_str = 'avocado' my_list = ['APPLE', 'BANANA', 'KIWI'] try: idx = [item.lower() for item in my_list].index(my_str.lower()) print(idx) except ValueError: print('Specified value is NOT present in the list')

The specified string is not present in the list, so a ValueError is raised and is handled by the except block.

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.