Python Sets

Sets in Python are a powerful data structure for storing unique elements. This article explains what sets are, how they work, and their key operations in Python. You’ll also learn about their benefits and practical applications to help you use them effectively.

Contents:

  1. Introduction to Python Sets
  2. Creating a Set in Python
  3. Properties of Sets in Python
  4. Adding Elements to a Set in Python
  5. Removing Elements from a Set in Python
  6. Set Operations in Python
  7. Checking Membership in a Set in Python
  8. Iterating Over a Set in Python
  9. Set Methods in Python
  10. Frozen Sets in Python
  11. Use Cases of Sets in Real-World Applications
  12. FAQs on Python Sets

Introduction to Python Sets

A set in Python stores unique elements in an unordered manner. It helps avoid duplicates when storing items. You can define a set using curly braces {} or the set() function.

Key Features of Sets

  • Unordered – Elements do not maintain a specific order.
  • Unique Elements – No duplicates are allowed.
  • Mutable – You can add or remove elements.
  • Heterogeneous – Can store different data types.
  • Unindexed – Elements cannot be accessed using an index.

Creating a Set in Python

A set is created by placing comma-separated values inside curly braces {} or by using the set() function.

advertisement

1. Creating a Set Using Curly Braces

Define a set with multiple elements.

subjects = {"Python", "Java", "DBMS", "AI"}
print(subjects)

Output:

🎓 Free Certifications on 300 subjects are live for December 2025. Register Now!
{'Python', 'Java', 'DBMS', 'AI'}

2. Creating a Set Using set() Function

Create a set from a list or tuple.

topics = set(["ML", "DL", "AI"])
print(topics)

Output:

advertisement
{'ML', 'DL', 'AI'}

3. Creating an Empty Set

Use set() to create an empty set.

empty_set = set()
print(type(empty_set))  # Check type

Output:

<class 'set'>

Note: Using {} creates an empty dictionary, not a set.

Properties of Sets in Python

A set in Python has unique characteristics that distinguish it from other data structures. Below are the key properties of sets:

1. Unordered

Sets do not maintain the order of elements. Element positions may change each time the set is printed.

subjects = {"Python", "Java", "DBMS", "AI"}
print(subjects)

Output:

{'Java', 'Python', 'DBMS', 'AI'}  # Order may vary

2. Unique Elements

Sets do not allow duplicate values. Duplicates are automatically removed.

subjects = {"Python", "Java", "Python", "DBMS"}
print(subjects)

Output:

{'Python', 'Java', 'DBMS'}

3. Mutable

You can add or remove elements from a set using methods like add(), remove(), and discard().

subjects = {"Python", "Java"}
subjects.add("DBMS")
print(subjects)

Output:

{'Python', 'Java', 'DBMS'}

4. Immutable Elements

The elements inside a set must be immutable (unchangeable), such as strings, numbers, and tuples.
Mutable types like lists and dictionaries cannot be added to a set.

# Valid elements
data = {1, "AI", (3, 4)}
print(data)
 
# Invalid elements (throws error)
# invalid_set = {["ML", "DL"]}

Output:

{1, 'AI', (3, 4)}

5. Heterogeneous Data Types

Sets can store elements of different data types.

data = {"Python", 101, 3.14, True}
print(data)

Output:

{'Python', 101, 3.14, True}

Adding Elements to a Set in Python

Python provides several built-in methods to add elements from a set. Since sets are mutable, you can modify them by adding new elements.

1. Using add() Method

The add() method adds a single element to a set. If the element already exists, it is not added again.

subjects = {"Python", "Java"}
subjects.add("DBMS")
print(subjects)

Output:

{'Python', 'Java', 'DBMS'}

2. Using update() Method

The update() method adds multiple elements (from lists, tuples, sets, etc.) to the set.

subjects = {"Python", "Java"}
subjects.update(["DBMS", "AI"])
print(subjects)

Output:

{'Python', 'Java', 'DBMS', 'AI'}

Removing Elements from a Set in Python

Python provides several built-in methods to remove elements from a set. Since sets are mutable, you can modify them by removing existing ones.

1. Using remove() Method

The remove() method removes a specific element from the set. If the element is not found, it raises a KeyError.

subjects = {"Python", "Java", "DBMS"}
subjects.remove("Java")
print(subjects)

Output:

{'Python', 'DBMS'}

2. Using discard() Method

The discard() method also removes a specific element, but unlike remove(), it does not raise an error if the element is not found.

subjects = {"Python", "Java", "DBMS"}
subjects.discard("Java")
print(subjects)
 
subjects.discard("AI")  # No error if element is not found
print(subjects)

Output:

{'Python', 'DBMS'}
{'Python', 'DBMS'}

3. Using pop() Method

The pop() method removes and returns a random element from the set. Since sets are unordered, you cannot predict which element will be removed.

subjects = {"Python", "Java", "DBMS"}
removed_item = subjects.pop()
print("Removed Item:", removed_item)
print(subjects)

Output:

Removed Item: Python
{'Java', 'DBMS'}

4. Using clear() Method

The clear() method removes all elements from the set, leaving it empty.

subjects = {"Python", "Java", "DBMS"}
subjects.clear()
print(subjects)

Output:

set()

Set Operations in Python

Python provides several built-in methods to perform mathematical operations on sets, such as union, intersection, difference, and symmetric difference. These operations help compare and manipulate sets effectively.

1. Union of Sets

The union operation combines all unique elements from two or more sets.

set1 = {"Python", "Java", "DBMS"}
set2 = {"AI", "ML", "DBMS"}
 
# Using union() method
result1 = set1.union(set2)
print(result1)
 
# Using | operator
result2 = set1 | set2
print(result2)

Output:

{'Python', 'Java', 'DBMS', 'AI', 'ML'}
{'Python', 'Java', 'DBMS', 'AI', 'ML'}

2. Intersection of Sets

The intersection operation returns elements that are common in both sets.

set1 = {"Python", "Java", "DBMS"}
set2 = {"AI", "DBMS", "ML"}
 
# Using intersection() method
result1 = set1.intersection(set2)
print(result1)
 
# Using & operator
result2 = set1 & set2
print(result2)

Output:

{'DBMS'}
{'DBMS'}

3. Difference of Sets

The difference operation returns elements present in one set but not in the other.

set1 = {"Python", "Java", "DBMS"}
set2 = {"AI", "DBMS", "ML"}
 
# Using difference() method
result1 = set1.difference(set2)
print(result1)
 
# Using - operator
result2 = set1 - set2
print(result2)

Output:

{'Python', 'Java'}
{'Python', 'Java'}

4. Symmetric Difference of Sets

The symmetric difference operation returns elements that are in either set, but not in both.

set1 = {"Python", "Java", "DBMS"}
set2 = {"AI", "DBMS", "ML"}
 
# Using symmetric_difference() method
result1 = set1.symmetric_difference(set2)
print(result1)
 
# Using ^ operator
result2 = set1 ^ set2
print(result2)

Output:

{'AI', 'Python', 'Java', 'ML'}
{'AI', 'Python', 'Java', 'ML'}

5. Subset and Superset Operations

  • Subset (<= or issubset()) → Checks if all elements of one set exist in another.
  • Superset (>= or issuperset()) → Checks if a set contains all elements of another.
set1 = {"Java", "DBMS"}
set2 = {"Python", "Java", "DBMS"}
print(set1.issubset(set2))  # Output: True
print(set2.issuperset(set1))  # Output: True

6. Disjoint Sets

The isdisjoint() method checks if two sets have no elements in common.

set1 = {"Python", "Java"}
set2 = {"AI", "ML"}
print(set1.isdisjoint(set2))  # Output: True

Checking Membership in a Set in Python

Membership operations in Python allow you to check whether an element is present in a set or not. This is done using the in and not in operators.

1. Using in Operator

The in operator checks if an element is present in the set. If the element exists, it returns True; otherwise, it returns False.

subjects = {"Python", "Java", "DBMS", "AI"}
 
# Check if "Python" is in the set
print("Python" in subjects)
 
# Check if "ML" is in the set
print("ML" in subjects)

Output:

True
False

2. Using not in Operator

The not in operator checks if an element is not present in the set.

subjects = {"Python", "Java", "DBMS", "AI"}
 
# Check if "ML" is not in the set
print("ML" not in subjects)
 
# Check if "Java" is not in the set
print("Java" not in subjects)

Output:

True
False

Iterating Over a Set in Python

Since sets are unordered collections of unique elements, you can iterate over them using loops. The most common way to iterate over a set is by using a for loop.

1. Using a for Loop

The most common method to iterate through a set.

True
# Define a set of subjects
subjects = {"Python", "Java", "DBMS", "AI"}
 
# Iterate using a for loop
for subject in subjects:
    print(subject)

Output:

Python
DBMS
Java
AI

(Note: The order may vary.)

2. Using for Loop with enumerate()

enumerate() adds an index while iterating.

True
subjects = {"Python", "Java", "DBMS", "AI"}
 
# Iterate with enumerate
for index, subject in enumerate(subjects):
    print(f"{index}: {subject}")

Output:

0: Python
1: DBMS
2: Java
3: AI

(Note: Order and index may vary.)

3. Using Set Comprehension

Create a new set by applying an operation on each element.

True
subjects = {"Python", "Java", "DBMS", "AI"}
 
# Create a new set with uppercase subjects
upper_subjects = {subject.upper() for subject in subjects}
print(upper_subjects)

Output:

{'PYTHON', 'DBMS', 'JAVA', 'AI'}

4. Using while Loop (Not Recommended)

Convert the set to a list for while loop iteration.

True
subjects = {"Python", "Java", "DBMS", "AI"}
subjects_list = list(subjects)
 
# Iterate using while loop
i = 0
while i < len(subjects_list):
    print(subjects_list[i])
    i += 1

Output:

Python
DBMS
Java
AI

Set Methods in Python

Python provides several built-in methods to work with sets efficiently. These methods allow you to modify sets, perform set operations, and retrieve specific information.

Method Description Example
add() Adds a single element to the set s.add(5)
update() Adds multiple elements to the set s.update([4, 5, 6])
remove() Removes an element (raises error if not found) s.remove(3)
discard() Removes an element (no error if not found) s.discard(3)
pop() Removes and returns a random element s.pop()
clear() Removes all elements from the set s.clear()
union() / | Returns the union of two sets A.union(B) or A | B
intersection() / & Returns common elements between two sets A.intersection(B) or A & B
difference() / – Returns elements in one set but not another A.difference(B) or A – B
symmetric_difference() / ^ Returns elements in either set but not both A.symmetric_difference(B) or A ^ B
issubset() / <= Checks if a set is a subset of another A.issubset(B) or A <= B
issuperset() / >= Checks if a set is a superset of another A.issuperset(B) or A >= B
isdisjoint() Checks if two sets have no elements in common A.isdisjoint(B)
copy() Returns a shallow copy of the set s.copy()
set() Converts another data type into a set set([1,2,3])

Frozen Sets in Python

A frozen set is an immutable version of a Python set that cannot be modified after creation. It is useful when you need to ensure that a set remains constant throughout the program.

Key Features of Frozen Sets:

  • Immutable – Cannot be changed after creation.
  • Hashable – Can be used as keys in dictionaries or elements of another set.
  • Similar to sets but with restricted operations.

1. Creating a Frozen Set

Use the frozenset() function to create a frozen set.

# Create a frozen set
subjects = frozenset(["Python", "Java", "DBMS", "AI"])
print(subjects)

Output:

frozenset({'Python', 'Java', 'DBMS', 'AI'})

2. Attempting to Modify a Frozen Set

Since a frozen set is immutable, attempting to modify it will raise an error.

subjects = frozenset(["Python", "Java", "DBMS"])
# Attempt to add an element (will raise an error)
subjects.add("AI")

Error:

AttributeError: 'frozenset' object has no attribute 'add'

3. Set Operations with Frozen Sets

Frozen sets support union, intersection, and difference operations, just like regular sets.
python

set1 = frozenset(["Python", "Java", "DBMS"])
set2 = frozenset(["DBMS", "AI"])
 
# Union
print(set1.union(set2))  # {'Python', 'Java', 'DBMS', 'AI'}
 
# Intersection
print(set1.intersection(set2))  # {'DBMS'}
 
# Difference
print(set1.difference(set2))  # {'Python', 'Java'}

Output:

frozenset({'Python', 'Java', 'DBMS', 'AI'})
frozenset({'DBMS'})
frozenset({'Python', 'Java'})

4. Using Frozen Sets as Dictionary Keys

Frozen sets can be used as keys in dictionaries because they are hashable.

# Using frozen set as a dictionary key
quiz_scores = {frozenset(["Python", "DBMS"]): 95, frozenset(["Java", "AI"]): 90}
print(quiz_scores)

Output:

{frozenset({'Python', 'DBMS'}): 95, frozenset({'Java', 'AI'}): 90}

Use Cases of Sets in Real-World Applications

Example 1: Removing Duplicates from Data

Sets automatically eliminate duplicate entries, making them ideal for cleaning datasets.

data = ["Python", "Java", "DBMS", "Java", "AI", "Python"]
unique_data = set(data)
print(unique_data)

Output:

{'Python', 'Java', 'DBMS', 'AI'}

Example 2: Managing Unique Usernames or IDs

Ensuring that user IDs or usernames are unique in a system.

usernames = {"sanf1", "sanf2", "sanf3"}
new_user = "sanf2"
 
if new_user not in usernames:
    usernames.add(new_user)
    print("User added!")
else:
    print("Username already exists.")

Output:

Username already exists.

Example 3: Event Tracking and Analytics

Sets can be used to track unique visitors or actions on a website.

visitors = {"user1", "user2", "user3"}
new_visitor = "user4"
 
# Add a new visitor
visitors.add(new_visitor)
print(visitors)

Output:

{'user1', 'user2', 'user3', 'user4'}

FAQs on Python Sets

1. What is a set in Python?
A set in Python is an unordered collection of unique elements. It does not allow duplicate values and is commonly used for mathematical set operations.

2. How do I create a set in Python?
A set can be created using curly braces {} or the set() function. Empty sets must be created using set(), as {} creates an empty dictionary.

3. How do I remove an element from a set?
The remove() method removes a specified element but raises an error if the element is not found. The discard() method removes an element without raising an error if the element is missing.

4. What is the difference between remove() and discard()?
The remove() method raises an error if the element is not found, whereas discard() does not.

5. How do I find the symmetric difference between two sets?
The symmetric_difference() method or ^ operator returns elements that are in either of the sets but not in both.

6. What is a frozen set?
A frozen set is an immutable version of a set. Once created, its elements cannot be modified, added, or removed.

7. How do I copy a set?
The copy() method creates a shallow copy of a set.

8. When should I use a set instead of a list?
Sets are useful when working with unique values, requiring fast lookups, or performing operations like union, intersection, and difference.

Key Points to Remember

Here is the list of key points we need to remember about “Python Sets”.

  • Sets in Python are unordered collections of unique elements, preventing duplicates and supporting operations like union, intersection, and difference.
  • Created using {} or set(), but {} alone creates an empty dictionary.
  • remove() deletes an element and raises an error if not found, discard() deletes without error, pop() removes a random element, clear() empties the set.
  • union() combines unique elements, intersection() finds common elements, difference() finds elements in one set but not another, symmetric_difference() finds elements in either but not both.
  • Membership is checked using in and not in.
  • Frozen sets are immutable, hashable, and used as dictionary keys, created using frozenset().

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.