tanay tanay - 4 months ago 9
Python Question

Pythonic way to check if a set in list is present in a different set

I have a list of sets

lst = [s1, s2, s3]


where

s1 = set([1, 2, 3])
s2 = set([2, 3, 4])
s3 = set([2, 4, 6])


and I have another set

set1 = set([1, 2, 3, 5])


So when I do
lst - set1
I should get
set()
. One way of doing this is just going through each element of
lst
and then do minus with
set1
. I want to know if there is any pythonic way of doing this.

For Example:

s1 = set([1, 2, 3, 4])
s2 = set([2, 3, 4])
s3 = set([2, 4, 6])

lst = [s1,s2,s3]

set1 = set([1, 2, 3, 5, 4])


So I need to check if any of the element in the list
lst
is present in
set1

Answer

To get a list of differences between sets you could use a list comprehension.

my_set = set([1, 2, 3, 5])

set_list = [
    set([1, 2, 3]),
    set([2, 3, 4]),
    set([2, 4, 6]),
]

# find differences between sets in list and my_set, remove empty sets
[set_item - my_set for set_item in set_list if set_item - my_set]
# returns [set([4]), set([4, 6])]

# to return only empty sets
[set_item - my_set for set_item in set_list if not set_item - my_set]

The list comprehension loops over your list of sets for set_item in set_list. It then ensures that the result set isn't empty if set_item - my_set. Finally, it returns the result set_item - my_set at the left side of the statement.