Python - Using set to work on sets with common objects

Introduction

You can use set to intersect/union two sets containing objects common to both categories.

Demo

engineers = {'jack', 'sue', 'ann', 'vic'} 
managers  = {'tom', 'sue'} 

print( 'bob' in engineers )                   # Is bob an engineer? 
print( engineers & managers )                # Who is both engineer and manager? 
print( engineers | managers )                 # All people in either category 
print( engineers - managers )                 # Engineers who are not managers 
print( managers - engineers )                 # Managers who are not engineers 
print( engineers > managers )                 # Are all managers engineers? (superset) 
print( {'bob', 'sue'} < engineers )           # Are both engineers? (subset) 
print( (managers | engineers) > managers )    # All people is a superset of managers 
print( managers ^ engineers )                 # Who is in one but not both? 
print( (managers | engineers) - (managers ^ engineers) )     # Intersection!
#  ww w  .ja  va2s  .  co m

Result

Related Topic