Sets in Python

 

What is a Set? 

A set in Python is an unordered collection of unique items. Think of it as a bag of marbles —you can have different colors, but no duplicates!

Why Use Sets?

  • No duplicates allowed 
  • Super fast lookups 
  • Mathematical set operations (union, intersection, etc.)

Creating a Set

Sets are created using curly brackets {} or the set() function.

fruits = {"apple", "banana", "cherry", "apple"}  # Duplicate 'apple' is ignored
print(fruits)  # Outputs: {'banana', 'apple', 'cherry'}

Empty Set?

To create an empty set, use set(), NOT {}.

empty_set = set()  # Correct 
empty_dict = {}    # This is a dictionary 

Adding and Removing Items

Add an item:

fruits.add("mango")
print(fruits)

Remove an item:

fruits.remove("banana")  # Error if not found
fruits.discard("cherry")  # No error if not found
print(fruits)

Set Operations

Union (Combine two sets):

a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)  # Outputs: {1, 2, 3, 4, 5}

Intersection (Common elements):

print(a & b)  # Outputs: {3}

Difference (Items in A but not in B):

print(a - b)  # Outputs: {1, 2}

Looping Through a Set

for fruit in fruits:
    print(fruit)

Summary

Concept Description
Set Unordered collection of unique items
Mutable Can add or remove elements
No Duplicates Automatically removes duplicates
Operations .add(), .remove(), .discard(), union (`

 

Post a Comment

0 Comments