Solve - ValueError: is not in list (Python)

avatar

Borislav Hadzhiev

Last updated: Apr 24, 2022

banner

Check out my new book

Solve - ValueError: is not in list (Python) #

The Python "ValueError: is not in list" occurs when we use the index() method with a value that is not present in the list. To solve the error, check if the value is in the list before using the index method, e.g. if 'value' in my_list:, or use a try/except block.

valueerror is not in list

Here is an example of how the error occurs.

main.py
my_list = ['apple', 'banana', 'kiwi'] # ⛔️ ValueError: 'melon' is not in list idx = my_list.index('melon')

We passed a value that is not in the list to the index() method which caused the error.

One way to solve the error is to check if the value is present in the list before calling the index() method.

main.py
my_list = ['apple', 'banana', 'kiwi'] if 'melon' in my_list: idx = my_list.index('melon') print(idx) else: # 👇️ this runs print('value is not in my 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.

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

main.py
my_list = ['apple', 'banana', 'kiwi'] result = my_list.index('banana') print(result) # 👉️ 1

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

You can also use a try/except statement to handle the scenario where the item is not in the list.

main.py
my_list = ['apple', 'banana', 'kiwi'] try: idx = my_list.index('melon') print(idx) except ValueError: print('item is not in the list') # 👉️ this runs

We call the index() method on the list and if a ValueError is raised, the except block is ran.

You can also use a one-liner if/else statement.

main.py
my_list = ['apple', 'banana', 'kiwi'] result_1 = my_list.index('melon') if 'melon' in my_list else None print(result_1) # 👉️ None result_2 = my_list.index('apple') if 'apple' in my_list else None print(result_2) # 👉️ 0
If the value is present in the list, we return the result of calling the index() method with the value, otherwise we return None.

If you have a two-dimensional list, make sure you are calling the index() method on the correct list.

main.py
my_list = [['apple', 'banana'], ['kiwi', 'mango']] idx = my_list[0].index('apple') print(idx) # 👉️ 0

We accessed the list item at index 0 and called the index() method on it.

Had we called the index() method on the outer list, we would get a ValueError because it doesn't contain the string "apple".

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.