Check if a string is present in multiple lists (Python)

Question:

What is 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

Check if string present in multiple lists (Python)

Asked By: Ant

||

Answers:

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])

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
Answered By: Simon S.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.