views:

71

answers:

3

Hi, i need to test if the user input is the same as an element of a list, right now i'm doing this

cars = ("red","yellow","blue")
guess = str(input())

if guess == cars[1] or guess == cars[2]:
        print ("success!")

But i'm working with bigger lists and my if statement is growing a lot with all those checks, is there a way to reference multiple indexes something like

if guess == cars[1] or cars[2]

I know that doesnt work, i wish i could just do

if guess == cars[1,2,3]

Reading the lists docs i saw that it's impossible to reference more than one index like i tried above and of course that sends a syntax error. Any help appreciated.

+1  A: 

Use guess in cars to test if guess is equal to an element in cars:

cars = ("red","yellow","blue")
guess = str(input())

if guess in cars:
        print ("success!")
unutbu
+1  A: 

Use in:

if guess in cars:
    print( 'success!' )

See also the possible operations on sequence type as documented in the official documentation.

poke
+7  A: 

The simplest way is:

if guess in cars:
    ...

but if your list was huge, that would be slow. You should then store your list of cars in a set:

cars_set = set(cars)
....
if guess in cars_set:
    ...

Checking whether something is present is a set is much quicker than checking whether it's in a list (but this only becomes an issue when you have many many items, and you're doing the check several times.)

(Edit: I'm assuming that the omission of cars[0] from the code in the question is an accident. If it isn't, then use cars[1:] instead of cars.)

RichieHindle
I think you misunderstood the question. In the first example his code would not print success if `guess` is `"red"`, but your code would.
sepp2k
Something to note here is that set construction, while efficient, may be a point of overhead if you're only checking the list once.
Daenyth
On the other hand, maybe I misunderstood and he simply made a mistake in his example code...
sepp2k
Thanks guys, yeah it was a mistake, but i'll keep that in mind, in, was what i needed :)
Guillermo Siliceo Trueba