Yogeesh Seralathan
Yogeesh Seralathan

Reputation: 1424

Check if an element in a list is present in multiple lists in python

I have to check if an element in list is present in multiple list.

Example:

cornerCase = [-1, 4]
top = [1, 2]
bottom = [2, 3]
left = [-1, 2]
right = [3,1]

In this case I have to check if -1 or 4 is present in any of the elements in top, bottom, left or right lists. Looking for a solution in more pythonic way.

My attempts:

1. 
    check = [i for i in cornerCase if i in top or bottom or left or right]

Didn't work. Realized after or it looks for other expression.

2.
    check = [i for i in cornerCase if i in (top, bottom, left, right)]

Damn! Didn't work again. Anyone please explain why ?

3.
    check = [i for i in cornerCase if i in [top, bottom, left, right]]

Obviously didn't work because checking a element in a list of lists.

I check if check != [] then -1 or 4 was found in those lists.

Any good pythonic way to achieve this ? Not looking for a solution with multiple for loops and individual if statements for all the lists.

Upvotes: 2

Views: 15589

Answers (4)

Yogeesh Seralathan
Yogeesh Seralathan

Reputation: 1424

As its just wanted to just check if -1 or 4 is present. any builtin function in python comes handy and returns True or False. So there won't be any need of if check != []:

>>> any(item in l for item in cornerCase for l in (top, bottom, left, right))
True

And Drashan's solution also works fine.

Upvotes: 2

Arthur Camara
Arthur Camara

Reputation: 577

The easiest way (and maybe not way too pythonic) is to simple iterate over cornerCase and check if any of these are in any of the other lists:

def check(cornerCase, top, left, bottom, right):
  for i in cornerCase:
    if i in top or i in left or i in bottom or i in right:
      return true
  return false

Upvotes: 0

Alessandro
Alessandro

Reputation: 31

Easy way: for c in cornerCase: if c in top or i in left or i in bottom or i in right: return true else return false

OR: List=[top,left,right,bottom] for c in cornerCase: if c in List return true else return false

Upvotes: 0

frunkad
frunkad

Reputation: 2543

Though It may not be a very nice solution but it works simple and well,

check = [i for i in cornerCase if i in top + bottom + left + right]

Upvotes: 9

Related Questions