The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Peaceful Mind

--

Chapters
00:00 Python How To Find Exact Match In A List And Not Just Contained In A Word Within List
00:51 Accepted Answer Score 5
01:05 Answer 2 Score 1
01:18 Answer 3 Score 1
01:40 Answer 4 Score 1
01:52 Thank you

--

Full question
https://stackoverflow.com/questions/4974...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 5


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



ANSWER 2

Score 1


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'



ANSWER 3

Score 1


@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')



ANSWER 4

Score 1


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!