heather heather - 2 months ago 5
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
name
". I can create the if statement; I just want to know what that command/method is.

Thanks!

Answer

Use the in operator.

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