The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC H Dvoks String Quartet No 12 Ame

--

Chapters
00:00 Question
01:03 Accepted answer (Score 5)
01:20 Answer 2 (Score 1)
01:38 Answer 3 (Score 1)
02:04 Answer 4 (Score 1)
02:21 Thank you

--

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

Answer 2 links:
[@Rakesh]: https://stackoverflow.com/users/532312/r...

--

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!