Majus457
Majus457

Reputation: 15

Python check variable against multiple lists

So I have 3 lists of data, I need to test if any of the data I get from the json response is in any of the lists, I'm probably being stupid about it but I'm trying to learn and can't seem to get it to work right.

list1 = ['a', 'b', 'c']
list2 = ['a1', 'b1', 'c1']
list2 = ['a2', 'b2', 'c2']

#block of code...
#block of code...

content = json.loads(response.read().decode('utf8'))
data = content
for x in data:
   #if x['name'] in list1: #This works fine the line below does not.
   if x['name'] in (list1, list2, list3):
   print("something")

Upvotes: 1

Views: 180

Answers (3)

Kasravnd
Kasravnd

Reputation: 107357

As a pythinc way for such tasks you can use any for simulating the OR operand and all for and operand.

So her you can use a generator expression within any() :

if any(x['name'] in i for i in (list1, list2, list3))

Upvotes: 1

Sam CD
Sam CD

Reputation: 2097

What about concatenating the lists?

if x['name'] in [list1 + list2 + list3]:

Upvotes: 0

Bryan Oakley
Bryan Oakley

Reputation: 386372

I suggest something simple and straight-forward:

if (x['name'] in list1 or 
    x['name'] in list2 or 
    x['name'] in list3):
    ...

Upvotes: 1

Related Questions