Sergio La Rosa
Sergio La Rosa

Reputation: 495

Python 3.5: search different values in a list

I have a list:

myList = [abc123, def456, ghi789, xyz999]

I need to search specific values in myList, based on this "sub-list" of allowed values:

allowed = [abc123, xyz999]

Edit: I need to check if myList contains the values in allowed

I already know how to seach for a specific substring in a list but I don't really understand how to do the same with a "sub-list".

Thank you in advance for your help.

Upvotes: 1

Views: 135

Answers (4)

Serge
Serge

Reputation: 3775

Assuming string lists (i.e. hashable):

set(a).intersect(set(b)) yield common elements

if need only boolean use issubset method: Python - verifying if one list is a subset of the other

for indvidual item search find, index Python: Find in list

Upvotes: 1

Ludisposed
Ludisposed

Reputation: 1769

I am not sure what you are trying to achieve, but I think you mean to look if the allowed values are in your list. So try this:

myList = ['abc123', 'def456', 'ghi789', 'xyz999']
allowed = ['abc123', 'xyz999']

for i in myList:
    if i in allowed:
        print("{0} in the list".format(i))

After reading your comments, the question is a bit vague, I made a solutions using a Dictionary to store the values of allowed and check wether all of them are in myList

myList = ['abc123', 'def456', 'ghi789', 'xyz999']
allowed = {'abc123' : False, 'xyz999' : False}

for i in myList:
    if i in allowed:
        allowed[i]=True

print((all(value == True for value in allowed.values())))

Upvotes: 2

Aran-Fey
Aran-Fey

Reputation: 43286

You can use set.issubset:

>>> set(allowed).issubset(myList)
True

Or, if your values aren't hashable, all with a comprehension:

>>> all(value in myList for value in allowed)
True

Upvotes: 2

Daniel Frühauf
Daniel Frühauf

Reputation: 311

for value in myList:
    if value in allowed:
        #dosomething

Upvotes: 1

Related Questions