Home > Mobile >  Check if string present in multiple lists (python)
Check if string present in multiple lists (python)

Time:01-12

Hoping someone can advise on the most efficient way to check whether a set string is present in all of three given lists, and if so, set itemInAllLists to True.

Below is the general idea of what I'm trying to achieve.

item = 'test-element'

list_a = ['a','random','test-element']
list_b = ['light','apple','table']
list_c = ['car','field','test-element','chair']

itemInAllLists = False

if item in [list_a] and item in [list_b] and item in [list_c]:
   itemInAllLists = True

CodePudding user response:

Have a look at the all built-in for Python, it will return True if all elements of an iterable is true.

If you put all your lists in a combined list you can do list comprehension to check each list.

all(item in all_lists for all_lists in [list_a, list_b, list_c])

Update

As deceze mentions you don't have to do it this way, what you are doing works as well and might be easier to read. Using all or any might be better suited for more lists or when you create them dynamically.

For your code to work you just have to remove the brackets so the syntax is correct:

if item in list_a and item in list_b and item in list_c:
    pass
  • Related