Python how to find exact match in a list and not just contained in a word within list

Question:

I’m trying to find an exact match for a word in a list of words either in a [] list or a list from a text document separated by a word per line. But using in returns true if the word is contained in the list of words. I’m looking for an exact match. For example in python 2.7.12:

mylist = ['cathrine', 'joey', 'bobby', 'fredrick']

for names in mylist:
    if 'cat' in names:
        print 'Yes it is in list'

this will return true, but I i want it to only be true if it’s an exact match. ‘cat’ should not return true if ‘cathrine’ is in mylist.

and trying to use if 'cat' == names: does’t seem to work.

How would I go about returning true only if the string I’m looking for is an exact match of a list of words, and not contained within a word of a list of words?

Asked By: positivetypical

||

Answers:

You can use in directly on the list.

Ex:

mylist = ['cathrine', 'joey', 'bobby', 'fredrick']

if 'cat' in mylist:
    print 'Yes it is in list'
#Empty


if 'joey' in mylist:
    print 'Yes it is in list'
#Yes it is in list
Answered By: Rakesh

You can use in with if else conditional operator

In [43]: mylist = ['cathrine', 'joey', 'bobby', 'fredrick']

In [44]: 'yes in list ' if 'cat' in mylist else 'not in list'
Out[44]: 'not in list'
Answered By: Roushan

@Rakesh Has given a answer to archive you task, This is just to make a correction to your statement.

 trying to use "if 'cat' == names:' does't seem to work

actually 'cat' == names this returns false the thing is your are missing the else part to catch that

mylist = ['cathrine', 'joey', 'bobby', 'fredrick']

for names in mylist:
    if 'cat' == names:
        print ('Yes it is in list')
    else:
        print('not in list')

You can use == instead of in

mylist = ['cathrine', 'joey', 'bobby', 'fredrick']

for names in mylist:
    if names =='cat' :
        print('Matched')
    else:
        print('Not Matched')

I think it will work!

Answered By: Sanjit Majee
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.