Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a word is in a list in Python

I am beginner in learning Python and have been practicing quit a bit however I have been having difficulties with a certain code I would like to write.

Essentially, I want to write a code which would analyse the word(s) in each list to check whether the word deer is indeed in the list mammals and print a certain message.

Here was my attempt:

myMammals = ['cow', 'cat', 'pig', 'man', 'woman']
ASCIIcodes = []
ASCII = x
for mammal in myMammals:
    for letter in mammal:
        x = ord(letter)
        ASCIIcodes.append(x)
print ASCIIcodes

animal = ['deer']
ASCIIcodes2 = []
ASCIIvalue = x
for word in animal:
    for letter in word:
        x = ord(letter)
        ASCIIcodes2.append(x)
print ASCIIcodes2

The code above, when run, returns:

[99, 111, 119, 99, 97, 116, 112, 105, 103, 109, 97, 110, 119, 111, 109, 97, 110]
[100, 101, 101, 114]

Reason why I wrote the code above was because I thought I could somehow create a list of the ascii codes of each character and then use those lists to do my comparison of the ascii codes as to check whether deer is indeed in the list of mammals

like image 714
Hobbes Avatar asked Feb 18 '17 14:02

Hobbes


1 Answers

I would suggest a function along the following:

def check(word, list):
    if word in list:
        print("The word is in the list!")
    else:
        print("The word is not in the list!")

This is assuming you're using Python 3.x, if you're using Python 2, then there shouldn't be parenthesis in your print statements

Hope this helps!

like image 83
Sishaar Rao Avatar answered Sep 26 '22 21:09

Sishaar Rao