0

let's say we have a list

a=["a1", "a2", "a3"]

then we have an input:

x=input("enter something: ")

how would you check if that input "x" is equal to any item in the list and then return true?

Coder Cody
  • 95
  • 1
  • 10
  • You can do `if x in a: return True`. – slider Nov 22 '18 at 18:06
  • it is not a duplicate of that article as i have a different situation – Coder Cody Nov 22 '18 at 18:12
  • How is it different? Can you be more specific? – slider Nov 22 '18 at 18:14
  • I didn't really want to disclose this information but I'm trying to make a naughts and crosses game and I've created lists to hold the data of each square in the naughts and crosses. I will then ask for an input and use that input, not to count how many times it repeats but use it to simply see whether the input correlates to a keyword to describe each square. I just did not find my answer on that particular post – Coder Cody Nov 22 '18 at 18:17
  • 1
    @slider Just `x in a` will do the trick. – Klaus D. Nov 22 '18 at 19:11

1 Answers1

1

You can check it with that code:

print("Yes, x in list" if x in a else "No, x is not in list")

It same that:

if x in a:
    print("Yes, x in list")
else:
    print("No, x is not in list")

Also if you want to get index of contained element - just use .index():

if x in a: 
    print('Yes, x in list, and it index is:', a.index(x))

In that example i'am avoid else: construct, but you can use it like in previous example, if you need it.

Andrey Topoleov
  • 1,591
  • 15
  • 20