Testing user input against a list in python

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

Leave a Comment