Login Register
×

What Is Python Set?

What Is a Set?

  • A Python set is a special collection of data that store inly unique values.
  • This means a set cannot contain duplicate items. If you try to add the same value twice, Python automatically keeps only one copy.
  • Imagine a set is a bag where you can put items in any order; this means the set does not maintain order.

Key Features of Sets In Python

  1. Unordered: A set does not add items in an index-based manner. The position of the elements may change when you print it.
  2. Unique Items: If you attempt to insert the same value multiple times, Python will retain only one copy.
  3. Mutable: It means you can still add new elements or remove existing ones.
  4. Unindexed: Sets do not support indexing or slicing.

How to Create a Set In Python?

In Python, we can create a set using curly braces {} or the built-in set() function.

Syntax of a Set:

set_name = {item1, item2, item3, ...}
  • You can always create an empty set with the following method:
empty_set = set()

# Because {} creates an empty dictionary, NOT an empty set.

Example 1: Creating a Set of Roll Numbers

# Set of roll numbers for today's attendance
roll_numbers = {12, 18, 21, 18, 27}
print("Unique roll numbers:", roll_numbers)

Output:

Unique roll numbers: {12, 18, 21, 27}
  • Here, duplicate value (18) removed and order NOT guaranteed.

Note: Using { } without elements creates an empty dictionary, not a set. Use set() to create an empty set.

Example 2: Creating an Empty Set Properly

# Creating an empty set to store incoming OTPs
otp_codes = set()
print("Empty set created:", otp_codes)

Output:

Empty set created: set()

How To Convert a List With Repeated City Names Into a Unique Set?

# Converting a list with repeated city names into a unique set
cities_list = ["Delhi", "Delhi", "Pune", "Goa", "Pune"]
unique_cities = set(cities_list)

print("Cities after removing duplicates:", unique_cities)

Output of the code:

Cities after removing duplicates: {'Delhi', 'Pune', 'Goa'}

How To Access Elements In a Set?

We can not access set elements using indexing like [0], [1], etc. Python gives us two simple ways to work with set elements.

1) Check if an Element Exists

We will use in keyword to check whether something is inside a set or not.

# A set of available colors in a design palette
palette = {"red", "blue", "green", "yellow"}

# Check if a color is in the palette
print("blue" in palette) # True
print("purple" in palette) # False
  • This is the fastest way to check values inside sets.

2) Loop Through the Set

  • You can also use a for-loop to access set elements. For example:
# Set of registered student names
students = {"Amit", "Sara", "Nina", "Rohan"}

# Print each name with a welcome message
for s in students:
print(f"Welcome, {s}!")

Output:

Welcome, Amit!
Welcome, Sara!
Welcome, Nina!
Welcome, Rohan!

Set Methods and Operations in Python

Python sets works with some built-in methods that help you add, remove, and manage elements easily.

MethodDescription
add(item)Adds a single item to the set.
update(iterable)Adds multiple items from an iterable (e.g., list, tuple).
remove(item)Removes an item. Raises an error if not found.
discard(item)Removes an item, and it doesn’t raise an error if not found.
pop()Removes and returns a random item.
clear()Removes all elements from the set.

1. Adding Elements to a Set

a) add(item) – This method inserts a single element into the set. For example:

# A set storing available book genres
genres = {"Fiction", "History"}

# Add a new genre to the library system
genres.add("Science")
print(genres)

Simple output:

{'Fiction', 'History', 'Science'}

b) update(iterable) – We can pass a list, tuple, or even another set to add multiple values at once.

# A set of sports offered in a college
sports = {"Cricket", "Football"}

# Add more sports from the list
sports.update(["Badminton", "Swimming"])
print(sports)

Output of the sports list:

{'Cricket', 'Football', 'Badminton', 'Swimming'}

2. Removing Elements from a Set

a) remove(item) – use when you want to remove an item from a set, and use only when you’re sure the item exists.

# Set of active sensors
sensors = {"Motion", "Temperature", "Smoke"}

# Remove a sensor that is no longer used
sensors.remove("Temperature")
print(sensors)

Output of a removed sensor:

b) discard(item) – Removes Item safely (No Error if Missing)

# Set of team members
team = {"Riya", "Kunal", "Meera"}

# Try removing someone (even if not in set)
team.discard("Aman") # No error
print(team)

Output:

c) pop() – Removes and returns a random item

# Set of online users in a game lobby
online_users = {"Arun", "Leena", "Jay", "Mira"}

# Remove a random user (maybe someone left the lobby)
removed_user = online_users.pop()

print("Removed:", removed_user)
print("Remaining:", online_users)

Output:

d) clear() – Remove all elements

# Set of saved draft emails
drafts = {"draft1", "draft2", "draft3"}

# Delete all drafts at once
drafts.clear()
print(drafts)

# Output: set()

3. Set Operations In Python

Sets support mathematical operations like union, intersection, difference and symmetric difference. let’s understand each:

OperationSyntaxDescription
Union`set1set2`
Intersectionset1 & set2Common elements between both sets.
Differenceset1 – set2Elements in set1 but not in set2.
Symmetric Differenceset1 ^ set2Elements in either set, but not both.

a) Union of Sets

  • Union returns every element that appears in either of the sets.
  • It combines both sets while automatically removing duplicates.
  • Operator: |
  • Method: set1.union(set2)
# Sets representing students from two different workshops
workshop_a = {"Rahul", "Sneha", "Aditi"}
workshop_b = {"Aditi", "Farhan", "Gaurav"}

# Combine all participants
all_participants = workshop_a | workshop_b
print(all_participants)

# Output: {'Rahul', 'Sneha', 'Aditi', 'Farhan', 'Gaurav'}

b) Intersection of Sets

  • Intersection returns only the values that exist in both sets.
  • Operator: &
  • Method: set1.intersection(set2)
# Devices that support App Version A and Version B
version_a = {"Android", "iOS", "Windows"}
version_b = {"iOS", "Linux", "Android"}

# Devices compatible with both versions
common_devices = version_a & version_b
print(common_devices)

# Output: {'Android', 'iOS'}

c) Difference of Sets

  • Difference tells you what is present in the first set but missing in the second.
  • Operator:
  • Method: set1.difference(set2)
# Features available in the premium plan
premium = {"Cloud Backup", "Dark Mode", "Analytics", "Priority Support"}

# Features in the free plan
free = {"Dark Mode"}

# Find premium-only features
exclusive_features = premium - free
print(exclusive_features)

# Output: {'Cloud Backup', 'Analytics', 'Priority Support'}

d) Symmetric Difference of Sets

  • Symmetric difference returns elements that are unique to each set — items that do NOT appear in both.
  • Operator: ^
  • Method: set1.symmetric_difference(set2)
# Students who participated on Day 1 and Day 2 of an event
day1 = {"Karan", "Meera", "Sahil"}
day2 = {"Meera", "Tara", "Rishi"}

# Students who attended only one day
unique_attendees = day1 ^ day2
print(unique_attendees)

# Output: {'Karan', 'Sahil', 'Tara', 'Rishi'}

e) Membership Tests (in / not in)

  • You can check whether an element exists inside a set.
# Set of cities where delivery service is active
active_cities = {"Delhi", "Mumbai", "Pune", "Surat"}

print("Pune" in active_cities) # True
print("Hyderabad" not in active_cities) # True

f) Copying a Set

  • If you want a new independent copy, use the copy() method.
# Original set of color themes
themes = {"Light", "Dark", "Blue"}

# Create a separate copy for customization
custom_themes = themes.copy()

print("Original:", themes)
print("Copied:", custom_themes)

Output of this code:

Original: {'Light', 'Dark', 'Blue'}
Copied: {'Light', 'Dark', 'Blue'}

What Is Frozenset In Python

A frozenset is a special version of a Python set, but with one major difference: it cannot be modified after creation. We can’t add, remove, or update elements.

The frozenset is useful when you need a constant, secure, unchangeable collection of unique values.

Example: How To Create a Frozenset

# Creating a frozenset of login roles
roles = frozenset(["viewer", "editor", "contributor"])

print("Assigned Roles:", roles)

Output will be something like:

Assigned Roles: frozenset({'viewer', 'editor', 'contributor'})