0

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?

6
  • "It is supposed to be only one line of code" - this smells of homework Commented Jan 26, 2015 at 8:17
  • I hate sentences like "it is supposed to be one line"... it is supposed to be good code, that's it. Commented Jan 26, 2015 at 8:17
  • It isn't. It's some pseudocode that my friend has been trying to crack. According to her peers, it is one line of code. Commented Jan 26, 2015 at 8:18
  • any(x in set_ for set_ in X)? Commented Jan 26, 2015 at 8:20
  • 1
    @KobiK to avoid shadowing the built-in set Commented Jan 26, 2015 at 8:25

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1
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.

Comments

0

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}

1 Comment

Just to note an alternative to the set-comp is 3 in set.union(*l) (but glglgl has already covered that one I see...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.