Skip to main content

4.4 - Working With Sets

A set in Python is an unordered collection of unique elements. Sets are defined by enclosing elements in curly braces {...} or using the set() function. They are particularly useful for membership testing, removing duplicates from a sequence, and mathematical operations like unions and intersections.

Sets are mutable, allowing the addition and removal of elements, but the elements themselves must be immutable. Sets do not record element position or order and do not support indexing, slicing, or other sequence-like behavior.

4.4.1 - Creating Sets

Sets are created using curly braces {} or the set() function:

# Creating an empty set
empty_set = set()

# Creating a set with elements
num_set = {1, 2, 3, 4, 5}

# Creating a set from a list
list_set = set([1, 2, 3, 4, 5])

Note: {} creates an empty dictionary, not a set. To create an empty set, use set().


4.4.2 - Adding Elements to Sets

Elements can be added to sets using the .add() method:

num_set.add(6)

4.4.3 - Removing Elements from Sets

Sets offer multiple methods for element removal:

  • .remove(element): Removes the element. Raises a KeyError if the element is not found.
  • .discard(element): Removes the element if it is present.
  • .pop(): Removes and returns an arbitrary element. Raises a KeyError if the set is empty.
  • .clear(): Removes all elements from the set.

Example:

num_set.remove(5)
num_set.discard(4)
num_set.pop()
num_set.clear()

4.4.4 - Set Operations

Sets support mathematical operations like union, intersection, difference, and symmetric difference:

  • Union: set1 | set2
  • Intersection: set1 & set2
  • Difference: set1 - set2
  • Symmetric Difference: set1 ^ set2

Example:

a = {1, 2, 3}
b = {3, 4, 5}

union = a | b # {1, 2, 3, 4, 5}
intersection = a & b # {3}
difference = a - b # {1, 2}
symmetric_difference = a ^ b # {1, 2, 4, 5}

4.4.5 - Checking Membership

To check if an element is in a set, use the in keyword:

if 1 in a:
print("1 is in the set")

4.4.6 - Set Length

The len() function returns the number of elements in a set:

length = len(a)

4.4.7 - Set Comprehensions

Set comprehensions allow for the concise creation of sets:

squared_set = {x**2 for x in range(6)}

4.4.8 - Converting Between Sets and Other Collections

Sets can be converted to and from other collection types:

# Set to list
set_list = list(a)

# List to set
new_set = set([1, 2, 3, 4, 5])

4.4.9 - Immutable Sets

Python also offers frozenset, an immutable version of a set:

immutable_set = frozenset([1, 2, 3])

4.4.10 - Summary Table of Set Operations and Features

Operation/FeatureDescriptionExample
Creating SetsDefine a set with {} or set().s = {1, 2, 3}
Adding ElementsAdd elements using .add().s.add(4)
Removing ElementsRemove elements using various methods.s.remove(4)
Set OperationsPerform union, intersection, etc.`union = a
Checking MembershipCheck if an element is in the set.if 1 in s: ...
Set LengthGet the number of elements in the set.len(s)
Set ComprehensionsConcisely create sets.squared = {x**2 for x in range(6)}
Converting CollectionsConvert between sets and other types.list_to_set = set([1, 2, 3])
Immutable SetsWork with unmodifiable frozenset.immutable = frozenset([1, 2, 3])