CIS 111 Sets

Objectives

  • Describe what a set is in Python
  • Create a set
  • Add an element to a set
  • Remove an element from a set
  • Access set documentation
  • Check for set membership
  • Use set operations (methods)
  • Use set comprehensions

Set overview

  • a set is an instance of the set class
  • documentation can be viewed using: help(set)
  • a set is an unordered collection of non-duplicated objects
  • sets are important when checking for existence
  • sets are not used for checking ordering
  • sets are not used for counting occurrences
  • have membership tests:
    • in
    • not in

Set examples

help(set) # displays set documentation people = set(['jacob', 'ann', 'shirley', 'isabelle']) # create set 'jacob' in people # True 'sam' in people # False print(len(people)) # 4 for nm in people: print(nm, end=' ') # ann jacob isabelle shirley people.add('marcus') people.add('jacob') # not added since it already exists print(people) # {'jacob', 'marcus', 'shirley', 'ann', 'isabelle'} set(['sharon','tom','ann','marcus']).union(people) # {'jacob', 'marcus', 'sharon', 'shirley', 'ann', 'isabelle', 'tom'} set(['sharon','tom','ann','marcus']).intersection(people) # {'ann', 'marcus'} people.difference(set(['tom','ann','jacob'])) # {'marcus', 'isabelle', 'shirley'} people.isdisjoint(set(['jacob'])) # False people.isdisjoint(set(['frank'])) # True people.issubset(set(['jacob'])) # False people.issuperset(set(['jacob'])) # True people.remove('arnie') # KeyError (value does not exist in set) people.discard('arnie') # OK, but does nothing # Examples of set comprehension set1 = set(range(10)) # create a work set print(set1) # {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} { 2**n for n in set1 } # {32, 1, 2, 64, 4, 128, 256, 512, 8, 16} { 2**n for n in set1 if n % 2 != 1 } # {64, 1, 256, 4, 16}