Sitemap
Saurabh Anand

Saurabh Anand

Data science enthusiast | Python & SQL learner | Exploring ML, statistics & visualization | Learning by building and sharing.

Python Sets Tutorial: Create, Modify, and Master

8 min readJun 25, 2026

--

Press enter or click to view image in full size
Figure: Python Sets Tutorial — No duplicates. Fast lookups. Pure Python.

When you learned about Python Lists, you saw how to store multiple values in one place. But what if you wanted to store a collection where no value repeats — ever?

Imagine you are tracking which players have scored a century in the Indian Cricket Team across different matches. A player like Virat Kohli may have scored centuries in many matches — but you only want to count him once in your collection. You don’t want duplicates. You just want unique names.

Is there a smarter way to handle this in Python?

Yes! And that smart container is called a SET in Python.

What You Will Learn in This Article

By the end of this article, you will be able to understand:

  • What is a Set in Python
  • Characteristics of a Set
  • How to Create a Set
  • Accessing Elements in a Set
  • Basic Operations on Sets (adding, removing data)
  • Set Methods
  • Set Operations (Union, Intersection, Difference)
  • Real-World Indian Examples using Cricket
  • Conclusion

What is a SET?

A Set is a built-in container in Python that stores multiple unique values in a single variable. It automatically removes duplicate entries, so you never have to worry about the same value appearing twice.

Think of it like the squad list for Team India — each player appears only once, no matter how many times their name is mentioned.

# Example: Unique century scorers for Team India
century_scorers = {"Virat Kohli", "Rohit Sharma", "Shubman Gill", "Virat Kohli"}
print(century_scorers)
# Output: {'Rohit Sharma', 'Virat Kohli', 'Shubman Gill'}
# Notice: 'Virat Kohli' appears only once even though we added it twice!

Why Use Python Sets?

  • No duplicates — automatically filters out repeated values, saving you manual effort
  • Fast lookup — checking if an item exists in a Set is much faster than in a List
  • Built-in mathematical operations — Union, Intersection, Difference make data comparison easy
  • Clean and simple — great for tasks like finding unique items, common elements, or differences between two groups
  • Used in real projects — from data cleaning to recommendation systems, Sets are everywhere

Characteristics of a Set

Python Sets have some important features that make them different from Lists and Tuples:

  • Unordered — Sets do not maintain any fixed order. The elements may appear in a different order every time you print them.
  • No Duplicates — A Set will never store two identical values. If you try to add a duplicate, Python simply ignores it.
  • Mutable — You can add or remove elements from a Set after it is created.
  • Does Not Support Indexing — Since Sets are unordered, you cannot access elements using an index like set[0].
  • Can Store Heterogeneous Data — A Set can hold integers, strings, floats, or tuples together.
  • Dynamic in Size — Elements can be added or removed at any time.
  • Elements Must Be Immutable — Individual elements inside a Set must be of immutable types (like strings, integers, or tuples). You cannot store a List inside a Set.

Creating a Set

There are two common ways to create a Set in Python:

1. Using Curly Brackets {}

The simplest and most common way. Elements are written inside {} and separated by commas.

Syntax:

set_name = {element1, element2, element3, ...}

# Empty set — NOTE: {} creates an empty Dictionary, NOT a Set
# So we must use set() for an empty set (explained below)

# Creating a Set with values
team_india = {"Rohit Sharma", "Virat Kohli", "Shubman Gill", "KL Rahul"}
print(team_india)
# Output: {'KL Rahul', 'Rohit Sharma', 'Virat Kohli', 'Shubman Gill'}

⚠️ Important: Writing {} alone creates an empty Dictionary, not a Set. Always use set() for an empty Set.

2. Using the set() Function

Used to create an empty Set, or to convert other data types (like Lists or Tuples) into a Set.

Get Saurabh Anand’s stories in your inbox

Join Medium for free to get updates from this writer.

Syntax:

set_name = set([element1, element2, element3, ...])

# Creating an empty set
empty_set = set()

# Converting a List into a Set (removes duplicates automatically)
players_list = ["Rohit", "Virat", "Rohit", "Gill", "Virat"]
unique_players = set(players_list)
print(unique_players)
# Output: {'Rohit', 'Gill', 'Virat'}

Accessing Elements in a Set

Since Sets are unordered, you cannot use indexing or slicing like you do with Lists.

# This will give an ERROR:
team_india = {"Rohit Sharma", "Virat Kohli", "Shubman Gill"}
print(team_india[0]) # ❌ TypeError: 'set' object is not subscriptable

Instead, you can loop through a Set using a for loop:

team_india = {"Rohit Sharma", "Virat Kohli", "Shubman Gill"}

for player in team_india:
print(player)
# Output (order may vary):
# Virat Kohli
# Rohit Sharma
# Shubman Gill

Or you can check if an element exists using the in keyword:

team_india = {"Rohit Sharma", "Virat Kohli", "Shubman Gill"}

print("Virat Kohli" in team_india) # Output: True
print("MS Dhoni" in team_india) # Output: False

Basic Operations on Sets (Adding and Removing Data)

1. Adding Elements to a Set

a) add() — Add a single element

team_india = {"Rohit Sharma", "Virat Kohli"}
team_india.add("Hardik Pandya")
print(team_india)
# Output: {'Rohit Sharma', 'Virat Kohli', 'Hardik Pandya'}

b) update() — Add multiple elements at once

team_india = {"Rohit Sharma", "Virat Kohli"}
team_india.update(["Shubman Gill", "KL Rahul", "Jasprit Bumrah"])
print(team_india)
# Output: {'Rohit Sharma', 'Virat Kohli', 'Shubman Gill', 'KL Rahul', 'Jasprit Bumrah'}

2. Removing Elements from a Set

a) remove() — Remove a specific element (raises error if not found)

team_india = {"Rohit Sharma", "Virat Kohli", "Shubman Gill"}
team_india.remove("Shubman Gill")
print(team_india)
# Output: {'Rohit Sharma', 'Virat Kohli'}

⚠️ If the element does not exist, remove() will raise a KeyError.

b) discard() — Remove an element (NO error if not found)

team_india = {"Rohit Sharma", "Virat Kohli"}
team_india.discard("MS Dhoni") # MS Dhoni is not in the set, but no error is raised
print(team_india)
# Output: {'Rohit Sharma', 'Virat Kohli'}

c) pop() — Remove and return a random element

team_india = {"Rohit Sharma", "Virat Kohli", "Shubman Gill"}
removed = team_india.pop()
print("Removed:", removed)
print(team_india)
# Output will vary because Sets are unordered

d) clear() — Remove all elements from the Set

team_india = {"Rohit Sharma", "Virat Kohli"}
team_india.clear()
print(team_india)
# Output: set()

Set Methods

Python provides several built-in methods for Sets. Here are the most useful ones:

1. copy() — Create a copy of the Set

team_india = {"Rohit Sharma", "Virat Kohli"}
backup = team_india.copy()
print(backup)
# Output: {'Rohit Sharma', 'Virat Kohli'}

2. len() — Get the number of elements

team_india = {"Rohit Sharma", "Virat Kohli", "Shubman Gill"}
print(len(team_india))
# Output: 3

3. issubset() — Check if one Set is a subset of another

playing_11 = {"Rohit Sharma", "Virat Kohli", "Shubman Gill"}
top_order = {"Rohit Sharma", "Virat Kohli"}

print(top_order.issubset(playing_11)) # Output: True

4. issuperset() — Check if one Set contains another Set

print(playing_11.issuperset(top_order))   # Output: True

5. isdisjoint() — Check if two Sets have NO elements in common

team_india = {"Rohit Sharma", "Virat Kohli"}
team_australia = {"Steve Smith", "David Warner"}

print(team_india.isdisjoint(team_australia)) # Output: True (no common players)

Set Operations — The Real Power of Sets

This is where Sets truly shine! Python Sets support mathematical set operations that are extremely useful for comparing data.

Press enter or click to view image in full size
Figure: Set Operations — Shaded region shows the result of each operation

1. Union — Combine both Sets (all unique elements)

Get all players from both India and Australia squads combined.

team_india = {"Rohit", "Virat", "Gill"}
team_australia = {"Warner", "Smith", "Gill"} # 'Gill' is in both (just for example)

all_players = team_india.union(team_australia)
print(all_players)
# Output: {'Rohit', 'Virat', 'Gill', 'Warner', 'Smith'}
# 'Gill' appears only once

You can also use the | operator:

all_players = team_india | team_australia

2. Intersection — Only Common Elements

Find players who are in both squads (e.g., dual-nationality players or common selections).

team_india = {"Rohit", "Virat", "Gill"}
team_australia = {"Warner", "Smith", "Gill"}

common = team_india.intersection(team_australia)
print(common)
# Output: {'Gill'}

You can also use the & operator:

common = team_india & team_australia

3. Difference — Elements in One Set but NOT the Other

Find players who are only in Team India and NOT in Team Australia.

team_india = {"Rohit", "Virat", "Gill"}
team_australia = {"Warner", "Smith", "Gill"}

only_india = team_india.difference(team_australia)
print(only_india)
# Output: {'Rohit', 'Virat'}

You can also use the - operator:

only_india = team_india - team_australia

4. Symmetric Difference — Elements NOT Common to Both

Find players who are in either team, but not in both.

team_india = {"Rohit", "Virat", "Gill"}
team_australia = {"Warner", "Smith", "Gill"}

unique_to_each = team_india.symmetric_difference(team_australia)
print(unique_to_each)
# Output: {'Rohit', 'Virat', 'Warner', 'Smith'}

You can also use the ^ operator:

unique_to_each = team_india ^ team_australia

Real-World Example — Cricket Stats Tracker

Let’s now put everything together with a practical Indian cricket example!

Press enter or click to view image in full size
Figure: Players who scored 50+ runs across two matches — the intersection shows consistent performers

Problem: You are given two lists of players who scored 50+ runs in two different ODI matches against Australia. You want to find:

  1. All players who scored 50+ in either match
  2. Players who scored 50+ in both matches (consistent performers)
  3. Players who scored 50+ in Match 1 only
# Players who scored 50+ in Match 1
match1_scorers = {"Rohit Sharma", "Virat Kohli", "Shubman Gill", "KL Rahul"}

# Players who scored 50+ in Match 2
match2_scorers = {"Virat Kohli", "Hardik Pandya", "Shubman Gill", "Suryakumar Yadav"}

# 1. All players who scored 50+ in either match
all_scorers = match1_scorers.union(match2_scorers)
print("All 50+ scorers:", all_scorers)
# Output: {'Rohit Sharma', 'Virat Kohli', 'Shubman Gill', 'KL Rahul', 'Hardik Pandya', 'Suryakumar Yadav'}

# 2. Players who scored 50+ in BOTH matches (consistent performers)
consistent = match1_scorers.intersection(match2_scorers)
print("Consistent performers:", consistent)
# Output: {'Virat Kohli', 'Shubman Gill'}

# 3. Players who scored 50+ in Match 1 ONLY
match1_only = match1_scorers.difference(match2_scorers)
print("Only in Match 1:", match1_only)
# Output: {'Rohit Sharma', 'KL Rahul'}

With just 3 lines of Set operations, you solved a problem that would have needed many loops and conditions if done with Lists. That is the power of Python Sets!

Conclusion

Python Sets are one of the most underrated yet powerful data types in Python. They shine whenever you need to:

  • Store unique values without duplicates
  • Perform fast membership checks
  • Compare two collections using Union, Intersection, or Difference

Whether you are a student tracking exam results, a developer building a recommendation system, or a cricket fan analysing player stats — Sets will make your code cleaner, faster, and smarter.

As you progress in your Python journey, Sets will become an essential tool in your programming toolkit. Make sure you practice the Set operations especially — they come up frequently in real-world data problems and technical interviews!

Happy Coding! 🏏

If you found this article helpful, don’t forget to clap and follow for more Python tutorials tailored.

--

--

Saurabh Anand
Saurabh Anand

Data science enthusiast | Python & SQL learner | Exploring ML, statistics & visualization | Learning by building and sharing.