TCG
TCG

Reputation: 121

How to Get a specific value from a list

I would like to know how to get a specific value from a list which can be anywhere in that list

I am using the code:

xl = []

while True:
    x = raw_input("enter 1 > ")
    xl.append(x)
    if xl == ["1"]:
        print "Thank you"

The program above only prints "Thank you" if the first input is '1'

I would like it so that the program could recognise the user input of '1' no matter where it is in the list.

I was thinking of doing something like this:

xl = []

while True:
    x = raw_input("enter 1 > ")
    xl.append(x)
    try:
        if xl == xl.index("1"):
            print "Thank you"
    except:
        continue

Thank you!

Upvotes: 0

Views: 349

Answers (1)

idjaw
idjaw

Reputation: 26570

You need to make use of the in keyword here. What you are trying to do is collect data in a list, and then check to see if a certain data exists anywhere in that list. Here is an example to help incorporate it in to your code:

my_list = [1, 2, 3, 4, 5]

if 3 in my_list:
    print('you found it')

Upvotes: 1

Related Questions