Python says string is not in list even though it is

Question:

I’m attempting to recreate Wordle as an exercise and need to get a guess from the user and then compare it to a list of valid words.

Even when I input a string that is in the list, it’s treated as if it isn’t.

        guessLoop = True
        while guessLoop == True:
            guess = str(input("Enter your guessn"))
            if guess in allValidGuesses:
                print(guess+' is a valid guess')
                guessLoop = False
            else:
                print(guess+' is not a valid guess')

I changed the code to this:

    guessLoop = True
    while guessLoop == True:
        allValidGuesses.append('test')
        guess = 'test'
        if guess in allValidGuesses:
            print(guess+' is a valid guess')
            guessLoop = False
        else:
            print(guess+' is not a valid guess')

To make sure the string was imported correctly, I made it print before it compares the guess. I also set the guess to a string that is in the list according to what it prints:

    guessLoop = True
    print(allValidGuesses)
    while guessLoop == True:
        guess = 'zoned'
        if guess in allValidGuesses:
            print(guess+' is a valid guess')
            guessLoop = False
        else:
            print(guess+' is not a valid guess')
            break

When it prints I can see that for "zoned" is in the list, but is still not considered a valid guess.

Output

Asked By: Sandstone6574

||

Answers:

I would recommend setting the code up in a way to make it easy to debug & test. This lets you inspect the code for issues very quickly.

Here is an example:


def check_guesses(allValidGuesses, debug=False):
  guessLoop = True
  while guessLoop == True:
    guess = str(input("Enter your guessn"))
    if guess in allValidGuesses:
      print(guess + ' is a valid guess')
      guessLoop = False
    else:
      print(guess + ' is not a valid guess')
      if debug:
        print("allValidGuesses: ", allValidGuesses)


def test1():
  check_guesses(allValidGuesses=["abc", "DEF"], debug=True)


test1()

When I run the code I get the following output & it seems to work correctly:

Enter your guess
a
a is not a valid guess
allValidGuesses:  ['abc', 'DEF']
Enter your guess
abc
abc is a valid guess
 

A few things to consider:

  1. Is allValidGuesses different from what you expect?
  2. Are there some issues with upper/lower casing?
Answered By: Aziz

In the screenshot of the output, you can see that the allValidGuesses list is a list of lists ie, [["foo"], ["bar"]], as opposed to ["foo", "bar"]
Therefore, "foo" in allValidGuesses will return False, whilst ["foo"] in allValidGuesses will return True

Answered By: jordan
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.