Check whether a value is in a list

You will often want to check if a certain value appears in a list, e.g. during a registration process to check whether the username already exists. This can be done using the in keyword:

names = ['Maria', 'Lucy', 'Angelina', 'Tanya']
new_name = 'Tanya'
if new_name in names:
    print('The name already exists. Please choose another one.')

In the example above we’ve created a list called names with four items in it. We’ve then assigned a value of Tanya to the variable new_name. Since the value of Tanya exists in the names lists, the message was displayed, informing the user that she needs to choose a new username.

Geek University 2022