Check if a user input value is in a List in Python

avatar

Borislav Hadzhiev

Last updated: Aug 22, 2022

banner

Photo from Unsplash

Check if a user input value is in a List in Python #

Use the in operator to check if a user input value is in a list, e.g. if user_input in my_list:. The in operator will return True if the input value is in the list and False otherwise.

main.py
# ✅ Check if user input value is in a string list my_list = ['apple', 'banana', 'kiwi'] user_input = input('Enter your favorite fruit: ') if user_input in my_list: print('The fruit is in the list') # --------------------------------------------- # ✅ Check if user input value is in a list of numbers my_list = [1, 3, 5, 7] user_input = 0 try: user_input = int(input('Enter your favorite number: ')) except ValueError: print('The provided value is not a valid integer') if user_input in my_list: print('The number is in the list') else: print('The number is NOT in the list')

check if input is in list

We used the in operator to check if a user input value is contained in a 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.

main.py
print('hi' in ['hi', 'world']) # 👉️ True print('hi' in ['one', 'two']) # 👉️ False

If you need to check if a value is not in a list, use the not in operator.

main.py
print('hi' not in ['hi', 'world']) # 👉️ False print('hi' not in ['one', 'two']) # 👉️ True

If you need to check if an input value is in a list of numbers, use the int() class to convert the value to an integer first.

main.py
my_list = [1, 3, 5, 7] user_input = 0 try: user_input = int(input('Enter your favorite number: ')) except ValueError: print('The provided value is not a valid integer') if user_input in my_list: print('The number is in the list') else: print('The number is NOT in the list')

check if input is in list for numbers

The input function takes an optional prompt argument and writes it to standard output without a trailing newline.

The function then reads the line from input, converts it to a string and returns the result.

The input() function is guaranteed to return a string, so we have to convert the value to an integer before checking for membership.

We used a try/except statement because the int() class raises a ValueError if the provided value is not a valid integer.

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.