Artemisia Artemisia - 4 months ago 7
Python Question

Python: searching within a list

Given an explicit list that comprises of sets that contain elements in each of them, how can I check whether a specific element is in the list or not? It is supposed to be only one line of code.

For example:

X
is a list. It contains sets
A
,
B
and
C
. Assume set
A
contains
{x, y, z}
,
B
contains
{l, m}
and
C
contains
{o, p}
. If I were to check whether
x
is in the list, how must I do it?

Answer

One approach can be to build a set containing the elements of all the sets in the list and check for existence of the element in this super set:

l = [{1},{2,3},{4,5}]
if 3 in {x for s in l for x in s}:
    print("Here you are!")

As you can see above, with set comprehension you can perform your check in just one line and in a quite pythonic way:

3 in {x for s in l for x in s}
Comments