2

I'm looking for a way to get the number of elements of one set that appear in another set.

Given these two sets:

a = 'a b c d'
b = 'a b c e f'
a = set(a.split())
b = set(b.split())

This prints false:

print a.issubset(b) # prints False

Is there a pythonic way to instead print "3" since three elements of a appear in b?

2 Answers 2

10

IIUC, you can use set.intersection:

>>> a.issubset(b)
False
>>> a.intersection(b)
{'a', 'c', 'b'}
>>> len(a.intersection(b))
3

which could be abbreviated & since both a and b are sets:

>>> len(a & b)
3
Sign up to request clarification or add additional context in comments.

Comments

1

You can you & and | to perform simple set algebra on python sets.

For example:

> a & b
set(['a', 'c', 'b'])
> a | b
set(['a', 'c', 'b', 'e', 'd', 'f'])

Comments

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.