Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing user input against a list in python

Tags:

python

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]

or

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.

like image 799
Guillermo Siliceo Trueba Avatar asked Dec 21 '25 14:12

Guillermo Siliceo Trueba


2 Answers

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.)

like image 74
RichieHindle Avatar answered Dec 24 '25 02:12

RichieHindle


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!")
like image 25
unutbu Avatar answered Dec 24 '25 04:12

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!