Sets in Python

A set is a collection of unique items. Sets are unordered and do not allow duplicates.

💡 Sets are written using curly brackets { }.

Creating a Set

numbers = {1, 2, 3, 4}
colors = {"red", "green", "blue"}

print(numbers)
print(colors)

No Duplicate Values

Duplicate values are automatically removed.

nums = {1, 2, 2, 3, 3, 4}
print(nums)

Adding & Removing Elements

fruits = {"apple", "banana"}

fruits.add("orange")
fruits.remove("banana")

print(fruits)

Set Operations

Sets support mathematical operations like union and intersection.

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

print(a | b)   # Union
print(a & b)   # Intersection
print(a - b)   # Difference

Checking Membership

langs = {"python", "java", "c++"}

print("python" in langs)
print("ruby" in langs)

When to Use Sets?

  • To remove duplicates
  • Fast membership testing
  • Mathematical operations

Practice Exercises

  1. Create a set of five numbers
  2. Add two new numbers
  3. Remove one number
  4. Find intersection of two sets