Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a value is equal to any value in an array [duplicate]

Tags:

python

I'm new to python (and programming in general) and I can't seem to find a solution to this by myself. I want to check the first letter of a string is equal to any letter stored in an array, something like this:

letter = ["a", "b", "c"]
word = raw_input('Enter a word:')
first = word[0]

if first == letter:
    print "Yep"
else:
    print "Nope"

But this doesn't work, does anyone know how it will? Thanks in advance!

like image 449
ThaRemo Avatar asked Aug 08 '13 18:08

ThaRemo


People also ask

How do you check if an array contains any element of another array?

Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.

How do you check if a number is repeated in an array in C?

int length = sizeof(arr)/sizeof(arr[0]); printf("Duplicate elements in given array: \n"); //Searches for duplicate element.


1 Answers

You need to use the in operator. Use if first in letter:.

>>> letter = ["a", "b", "c"]
>>> word = raw_input('Enter a word:')
Enter a word:ant
>>> first = word[0]
>>> first in letter
True

And one False test,

>>> word = raw_input('Enter a word:')
Enter a word:python
>>> first = word[0]
>>> first in letter
False
like image 189
Sukrit Kalra Avatar answered Oct 14 '22 15:10

Sukrit Kalra