Artemisia
Artemisia

Reputation: 133

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?

Upvotes: 0

Views: 108

Answers (3)

glglgl
glglgl

Reputation: 91139

x = [set((1, 2, 3)), set((4, 5)), set((6, 7))]
print set.union(*x)
print 1 in set.union(*x)
print 8 in set.union(*x)

creates a set of the union of all present sets. Using this, checking for presence is trivial.

Upvotes: 1

Bartosz Marcinkowski
Bartosz Marcinkowski

Reputation: 6881

I guess the line is any(x in s for s in l) like in

>>> l = [{1, 2, 3}, {4, 5}, {6}]
>>> x = 5
>>> any(x in s for s in l)
True

It has the added benefit on not creating new instances, not touching further sets after x is found and it does not depend on the fact that l contains sets (it could be anything iterable as well).

Upvotes: 1

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}

Upvotes: 0

Related Questions