Data Structures

Sets

A set is an unordered collection with no duplicates.

Creating Sets

numbers = {1, 2, 3, 4, 5}
unique_letters = set("hello")  # {'h', 'e', 'l', 'o'}

Automatic Duplicate Removal

numbers = {1, 2, 2, 3, 3, 3}
print(numbers)  # {1, 2, 3}

Set Operations

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

a | b   # Union: {1, 2, 3, 4, 5}
a & b   # Intersection: {3}
a - b   # Difference: {1, 2}

Common Uses

  • Remove duplicates from a list
  • Check membership quickly
  • Mathematical set operations
Visualizer
$ python sets.py
Unique: {'Alice', 'Bob', 'Charlie'} Union: {1, 2, 3, 4, 5, 6} Intersection: {3, 4}

Interactive Visualization

python
Loading...
Output
Run execution to see output...