Sets

15 min In Progress

Learning Objectives

  • Create unordered collections of unique items
  • Perform set operations: union, intersection, difference
  • Remove duplicates from data

Set Basics

Sets are unordered collections with no duplicates.

numbers = {1, 2, 3, 3, 3}
print(numbers)
numbers.add(4)
numbers.remove(2)
print(numbers)

Set Operations

Perform mathematical set operations.

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b)   # union
print(a & b)   # intersection
print(a - b)   # difference

Course Example: Set Maker

Convert a list to a set to remove duplicates.

def set_maker(the_list):
  return set(the_list)

print(set_maker([1, 2, 2, 3, 3, 3]))

Course Example: Find Union

Manually compute the union of two lists without duplicates.

def find_union(list_a, list_b):
  union = []
  for element in list_a + list_b:
    if element not in union:
      union.append(element)
  return union

print(find_union([1, 2, 3], [2, 3, 4]))

📝 Exercise: Unique Words

Split a sentence into words and create a set of unique words.

code.py
Output

            
← Back to Chapter