2
votes

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.

4
Is it intentional that you're not looking at cars[0]? Lists are indexed from zero, so your three cars are cars[0], cars[1] and cars[2]. - RichieHindle
i really hope you're using python 3.x...otherwise use raw_input instead of input and print 'succes!', without brackets - Ant
Yeah i'm aware of the 0 index in list thanks, And yes it is python 3.1 - Guillermo Siliceo Trueba

4 Answers

10
votes

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

2
votes

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!")
2
votes

Use in:

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

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

0
votes

@Sean Hobbs: First you'd have to assign a value to the variable index.

index = 0

You might want to use while True to create the infinite loop, so your code would be like this:

while True:

    champ = input("Guess a champion: ")
    champ = str(champ)

    found_champ = False
    for i in listC:
        if champ == i:
            found_champ = True

    if found_champ:
        print("Correct")
    else:
        print("Incorrect")