Skip to content

Instantly share code, notes, and snippets.

@luisenriquecorona
Created April 18, 2019 17:42
Show Gist options
  • Save luisenriquecorona/2047a8110f170ca3faca898fb0676081 to your computer and use it in GitHub Desktop.
Save luisenriquecorona/2047a8110f170ca3faca898fb0676081 to your computer and use it in GitHub Desktop.
Set comprehensions in Python 3.X and 2.7
>>> engineers = {'bob', 'sue', 'ann', 'vic'} >>> managers = {'tom', 'sue'}
>>> 'bob' in engineers True
>>> engineers & managers {'sue'}
>>> engineers | managers
{'bob', 'tom', 'sue', 'vic', 'ann'}
>>> engineers - managers {'vic', 'ann', 'bob'}
>>> managers - engineers {'tom'}
>>> engineers > managers False
# Is bob an engineer?
# Who is both engineer and manager?
# All people in either category
# Engineers who are not managers
# Managers who are not engineers
# Are all managers engineers? (superset)
>>> {'bob', 'sue'} < engineers True
>>> (managers | engineers) > managers True
>>> managers ^ engineers {'tom', 'vic', 'ann', 'bob'}
# Are both engineers? (subset)
# All people is a superset of managers # Who is in one but not both?
>>> (managers | engineers) - (managers ^ engineers) # Intersection! {'sue'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment