Python Sets Explained with Examples (Beginner to Advanced Guide)

← Back to Home

Learn Python Sets Step-by-Step (With Code, Use Cases, and Operations)


Python provides versatile built-in data types, and set is one of the most practical for working with unique values and performing set operations like union, intersection, and difference.

In this guide, we’ll break down sets in Python with simple examples and practical use cases, making it easy for both beginners and experienced programmers to understand.



What is a Set in Python?

A set is an unordered collection of unique elements. Unlike lists or tuples, sets do not keep items in a particular order and automatically eliminate duplicates.

Sets are ideal for checking membership quickly, removing duplicates, and performing mathematical operations like union and intersection.

my_set = {10, 20, 30, 40}
print(my_set)

✅ Output:

{10, 20, 30, 40}


How to Create Sets in Python


1. Using Curly Braces

Sets can be created using curly braces as shown below:

colors = {"red", "green", "blue"}

2. Using the set() Constructor

numbers = set([11, 22, 33, 44])

❌ Duplicate Values Are Removed Automatically

data = {5, 5, 7, 8}
print(data)  # Output: {5, 7, 8}


Key Features of Sets

Feature Description
UnorderedNo fixed index for items
Unique itemsDuplicates are automatically removed
MutableItems can be added or removed
IterableCan loop through items


Basic Set Operations


Add Items

my_set = {100, 200}
my_set.add(300)
print(my_set)  # {100, 200, 300}

Remove Items

my_set.remove(200)  # Raises error if not found
my_set.discard(400)  # Ignores if not found

Check Membership

if "red" in colors:
    print("Found!")


Set Operations: Like Math Sets


Let’s take two example sets:

A = {1, 3, 5, 7}
B = {3, 5, 9, 11}

Union (All unique elements)

print(A | B)  # {1, 3, 5, 7, 9, 11}

Intersection (Common elements)

print(A & B)  # {3, 5}

Difference (Items in A not in B)

print(A - B)  # {1, 7}

Symmetric Difference (Items not in both)

print(A ^ B)  # {1, 7, 9, 11}


When to Use Sets in Real Projects?

  • Remove duplicates from a list
  • Fast membership checking (much faster than lists)
  • Compare collections of values
  • Data cleaning and deduplication


Limitations of Sets

  • ❌ Cannot access items by index or slice (e.g., my_set[0] is invalid)
  • ❌ Cannot store mutable objects like lists


Set vs List vs Tuple (Quick Comparison)

Feature List Tuple Set
Ordered
Mutable
Duplicates
Indexed


Example: Remove Duplicates from a List

items = [10, 20, 20, 30, 40, 40, 50]
unique_items = list(set(items))
print(unique_items)  # [10, 20, 30, 40, 50]


🧾 Conclusion

Python sets are a powerful tool for handling unique data, cleaning collections, and performing fast comparisons. They are simple to use but extremely useful in real-world applications like data science, web development, and automation.

If you already know lists and dictionaries, mastering sets adds another essential tool to your Python toolkit.



🔧 Advanced Set Features (For Experienced Learners)

Python sets are simple to begin with, but they also provide several advanced features that are extremely useful once you start working on large applications, data processing, or performance-focused programs. Below are some professional-level concepts explained in an easy and beginner-friendly way.


1. Set Comprehension

Set comprehension is similar to list comprehension but creates a set instead of a list. It provides a short and efficient way to generate sets dynamically.


# Create a set of squares using set comprehension
squares = {num * num for num in range(1, 8)}
print(squares)  # Example: {1, 4, 9, 16, 25, 36, 49}

This is especially useful for filtering data, generating unique values, or working with mathematical problems.


2. Frozen Sets (Immutable Sets)

A frozenset is like a regular set, except it cannot be changed after creation. That means you cannot add or remove elements. It is useful when you need a set that must remain constant throughout your program.


# Creating an immutable set
frozen_items = frozenset(["pen", "notebook", "marker"])
print(frozen_items)

You can use frozensets as keys in dictionaries or elements inside another set, because they are hashable.


3. Advanced Set Methods

✔ issubset()

Checks if all elements of one set exist inside another set.


A = {1, 2}
B = {1, 2, 3, 4}
print(A.issubset(B))  # True

✔ issuperset()

Checks if a set contains all elements of another set.


print(B.issuperset(A))  # True

✔ isdisjoint()

Returns True if two sets share no common elements.


X = {100, 200}
Y = {300, 400}
print(X.isdisjoint(Y))  # True

4. Copying Sets

To avoid modifying the original set, use the copy() method to make a separate duplicate.


colors = {"red", "green", "blue"}
saved_copy = colors.copy()
print(saved_copy)

5. Set Performance Notes

One of the biggest advantages of sets is speed. Set lookups and membership checks like if item in my_set are extremely fast due to hashing.

  • Searching in a list → ❌ slower (O(n))
  • Searching in a set → ✅ very fast (O(1))

This makes sets a great choice when you need high-speed filtering, duplicate removal, or large-scale comparisons.


📌 FAQ: Python Sets

  • Q1: Can a set contain duplicate values?
    No. Sets automatically remove duplicate values.
  • Q2: Can sets store lists inside them?
    No. Sets can only contain immutable items like numbers, strings, and tuples.
  • Q3: How do I add or remove elements?
    Use add() to add and remove() or discard() to remove elements.
  • Q4: Are sets ordered?
    No. The order of elements in a set is not guaranteed.
  • Q5: Why use sets over lists?
    Sets are faster for membership checking and automatically remove duplicates.


🚀 It's time to Action

If you found this guide helpful:

  • Start experimenting with Python sets in your projects today.
  • Try creating sets from your favorite numbers, words, or even daily tasks.
  • Don’t forget to share this guide with your friends and colleagues learning Python.