Skip to content

Python Sets (Set)

Sets are another important data type in Python. They are unordered collections that do not contain duplicate elements. The main purpose of sets is for membership testing and eliminating duplicate entries.

Creating Sets

Sets are defined using curly braces {}, or using the set() constructor.

python
# Create a set using curly braces
fruits = {"apple", "banana", "cherry"}
print(fruits)

# Create a set from a list using set() constructor
# Note: duplicate elements are automatically removed
numbers_list = [1, 2, 2, 3, 4, 4, 4]
numbers_set = set(numbers_list)
print(numbers_set)  # Output: {1, 2, 3, 4}

# Create a set from a string
char_set = set("hello world")
print(char_set) # Output: {'o', 'd', 'l', 'h', ' ', 'w', 'r', 'e'}

Note: Creating an empty set

You cannot use {} to create an empty set, as this would create an empty dictionary. To create an empty set, you must use set().

python
empty_dict = {}
empty_set = set()

print(type(empty_dict)) # Output: <class 'dict'>
print(type(empty_set))  # Output: <class 'set'>

Set Characteristics

  1. Unordered: Elements in a set have no specific order. You cannot access elements in a set by index (e.g., my_set[0] will raise an error).
  2. Uniqueness: Sets cannot contain duplicate elements. This is the core characteristic of sets.
  3. Mutable: Sets themselves are mutable, you can add or remove elements from them.

Common Set Methods

  • set.add(elem): Adds an element to the set.
  • set.update(iterable): Updates the set with all elements from another iterable.
  • set.remove(elem): Removes an element from the set. If the element doesn't exist, raises KeyError.
  • set.discard(elem): Removes an element from the set. If the element doesn't exist, does not raise an error.
  • set.pop(): Removes and returns a random element from the set. If the set is empty, raises KeyError.
  • set.clear(): Removes all elements from the set.

Example:

python
my_set = {1, 2, 3}

my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}

my_set.update([4, 5, 6])
print(my_set) # Output: {1, 2, 3, 4, 5, 6}

my_set.remove(1)
print(my_set) # Output: {2, 3, 4, 5, 6}

my_set.discard(10) # Element 10 doesn't exist, but won't raise error
print(my_set)

Set Operations

Sets' most powerful feature is their mathematical operations, which can be used to compare the relationship between two sets.

Let's assume we have two sets:

python
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
  • Union: Returns a new set containing all elements from both sets.

    • A | B
    • A.union(B)
    • Result: {1, 2, 3, 4, 5, 6}
  • Intersection: Returns a new set containing only the elements that exist in both sets.

    • A & B
    • A.intersection(B)
    • Result: {3, 4}
  • Difference: Returns a new set containing elements that exist in the first set but not in the second set.

    • A - B (elements in A, not in B)
    • A.difference(B)
    • Result: {1, 2}
  • Symmetric Difference: Returns a new set containing all elements that appear in only one of the two sets (i.e., union minus intersection).

    • A ^ B
    • A.symmetric_difference(B)
    • Result: {1, 2, 5, 6}

Example:

python
print(f"Union: {A | B}")
print(f"Intersection: {A & B}")
print(f"Difference (A-B): {A - B}")
print(f"Symmetric Difference: {A ^ B}")

Content is for learning and research only.