Sets (unordered data with optimized logic operations)

Data Types in Python

Jason Myers

Instructor

Set

  • Unique
  • Unordered
  • Mutable
  • Python's implementation of Set Theory from Mathematics
Data Types in Python

Creating sets

  • Sets are created from a list
cookies_eaten_today = ['chocolate chip', 'peanut butter', 
   ...: 'chocolate chip', 'oatmeal cream', 'chocolate chip']

types_of_cookies_eaten = set(cookies_eaten_today)
print(types_of_cookies_eaten)
set(['chocolate chip', 'oatmeal cream', 'peanut butter'])
Data Types in Python

Modifying sets

  • .add() adds single elements
types_of_cookies_eaten.add('biscotti')

types_of_cookies_eaten.add('chocolate chip')

print(types_of_cookies_eaten)
set(['chocolate chip', 'oatmeal cream', 'peanut butter', 'biscotti'])
Data Types in Python

Updating sets

  • .update() merges in another set or list
cookies_hugo_ate = ['chocolate chip', 'anzac']

types_of_cookies_eaten.update(cookies_hugo_ate)

print(types_of_cookies_eaten)
set(['chocolate chip', 'anzac', 'oatmeal cream',  'peanut butter', 'biscotti'])
Data Types in Python

Removing data from sets

  • .discard() safely removes an element from the set by value
  • .pop() removes and returns an arbitrary element from the set (KeyError when empty)
types_of_cookies_eaten.discard('biscotti')

print(types_of_cookies_eaten)
set(['chocolate chip', 'anzac', 'oatmeal cream', 'peanut butter'])
types_of_cookies_eaten.pop()
types_of_cookies_eaten.pop()
'chocolate chip'
'anzac'
Data Types in Python

Set operations - similarities

  • .union() set method returns a set of all the names (or)
  • .intersection() method identifies overlapping data (and)
cookies_jason_ate = set(['chocolate chip', 'oatmeal cream',
'peanut butter'])
cookies_hugo_ate = set(['chocolate chip', 'anzac'])

cookies_jason_ate.union(cookies_hugo_ate)
set(['chocolate chip', 'anzac', 'oatmeal cream', 'peanut butter'])
cookies_jason_ate.intersection(cookies_hugo_ate)
set(['chocolate chip'])
Data Types in Python

Set operations - differences

  • .difference() method identifies data present in the set on which the method was used that is not in the arguments (-)
  • Target is important!
cookies_jason_ate.difference(cookies_hugo_ate)
set(['oatmeal cream', 'peanut butter'])
cookies_hugo_ate.difference(cookies_jason_ate)
set(['anzac'])
Data Types in Python

Let's practice!

Data Types in Python

Preparing Video For Download...