🔢 Set in Python

🔹 What is a Set in Python?

A set in Python is a built-in data structure that stores unique elements in no particular order. Sets are mutable, but their elements must be immutable (numbers, strings, tuples).

👉 Sets are useful for union, intersection, difference, and fast membership testing.

Article Algo

✅ Why Use Sets?

  • Automatically removes duplicate values
  • Fast membership testing
  • Supports mathematical set operations
  • Efficient for data deduplication

📌 Creating a Set

# Using curly braces
fruits = {"apple", "banana", "cherry"}

# Using set() constructor
numbers = set([1, 2, 3, 4])

🔸 Empty Set

empty_set = set()   # {} creates an empty dictionary

📌 Characteristics of Sets

  • Unordered: No fixed position of elements
  • Unique: Duplicate elements are removed automatically
  • Mutable: Elements can be added or removed
  • No indexing or slicing

📌 Accessing Set Elements

Since sets are unordered, elements cannot be accessed by index.

fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
  print(fruit)

📌 Adding Elements to a Set

fruits.add("orange")
fruits.update(["mango", "kiwi"])

📌 Removing Elements from a Set

fruits.remove("banana")   # Error if not found
fruits.discard("banana")  # No error
fruits.pop()         # Removes random element
fruits.clear()      # Removes all elements

📌 Set Operations

Python sets support mathematical operations.

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

print(A | B)  # Union
print(A & B)  # Intersection
print(A - B)  # Difference
print(A ^ B)  # Symmetric Difference

📚 Set Methods

Method Description
add() Adds an element
update() Adds multiple elements
remove() Removes an element
discard() Removes element without error
pop() Removes a random element
clear() Removes all elements
union() Returns union of sets
intersection() Returns common elements
difference() Returns difference
symmetric_difference() Returns non-common elements

📌 Set Comprehension

Create sets in a single line.

squares = {x*x for x in range(1, 6)}

✅ Advantages of Sets

  • Ensures unique elements
  • Supports fast membership tests
  • Ideal for mathematical operations
  • Efficient for removing duplicates

❌ Disadvantages of Sets

  • Unordered (no indexing)
  • Cannot store mutable elements
  • No duplicate values allowed

📊 Set vs List (Quick Comparison)

Feature Set List
Order Unordered Ordered
Duplicates No Yes
Indexing No Yes
Mutability Mutable Mutable
Operations Union, Intersection No direct support

🌍 Real-World Use Cases

  • Removing duplicates from data
  • Fast membership testing
  • Mathematical operations
  • Tagging systems
  • Data cleaning in data science