heather heather - 1 year ago 53
Python Question

Checking if a variable is existent within a list

I am currently using the code

names = ["Bob", "Joe", "Jack"]
name = raw_input("Please enter your name.")
print ("Hello", name)

And I want to create an if statement that checks if the inputed name is in the list of names. I assume there is some command to check this, and I couldn't find it searching the documentation or questions here. Right now, the code creates a list of names, a variable that stores the inputed name, and prints "Hello
". I can create the if statement; I just want to know what that command/method is.


Answer Source

Use the in operator.

if name in names:
    print ('The entered name is in the list of names.')
    print ('The entered name is not in the list of names.')