How to make a set in Python
Learn how to create sets in Python. This guide covers different methods, tips, real-world applications, and how to debug common errors.

Python sets are unordered collections of unique items, perfect when you need to test for membership or eliminate duplicates. You can create them with curly braces {} or the set() function.
You'll discover various creation techniques, get practical tips, and see real-world applications. This article also provides advice to debug common issues so you can master sets for efficient data work.
Creating a simple set
fruits = {"apple", "banana", "cherry"}
print(fruits)
print(type(fruits))--OUTPUT--{'cherry', 'banana', 'apple'}
<class 'set'>
This example demonstrates the most direct way to create a set. The output reveals a core characteristic: sets are unordered. The items in fruits don't appear in the same sequence they were defined in.
This isn't random; it's a key part of what makes sets efficient for checking if an item is present. The type() function confirms you've created a <class 'set'>, not a dictionary, which also uses curly braces but for key-value pairs.
Basic set creation and modification
While defining a set with curly braces works for simple scenarios, you'll often need to create them from other data structures or modify their contents.
Creating sets from other data structures
numbers_list = [1, 2, 2, 3, 4, 4, 5]
numbers_set = set(numbers_list)
print("Original list:", numbers_list)
print("Set from list:", numbers_set)--OUTPUT--Original list: [1, 2, 2, 3, 4, 4, 5]
Set from list: {1, 2, 3, 4, 5}
The set() constructor is a powerful tool for converting other iterables, like lists, into sets. When you pass a list such as numbers_list to set(), Python iterates through it and builds a new set containing only the unique elements.
- Notice how the duplicate values
2and4from the original list are automatically discarded. - This makes the
set()function a concise and highly efficient method for deduplicating data from any iterable.
Adding elements with add() and update()
colors = {"red", "green"}
colors.add("blue")
colors.update(["yellow", "orange"])
print(colors)--OUTPUT--{'red', 'blue', 'yellow', 'orange', 'green'}
You can dynamically modify sets after they're created. The add() method is straightforward; it inserts a single new element. If the element already exists, the set simply remains unchanged, which is how it enforces uniqueness.
- Use
add()for one item at a time, like when"blue"was added to the set. - Use
update()to absorb multiple items from an iterable, such as the list containing"yellow"and"orange".
This distinction makes your code's intent clear and efficient when you need to expand a set's contents.
Removing elements with remove(), discard(), and pop()
animals = {"dog", "cat", "bird", "fish"}
animals.remove("bird")
animals.discard("elephant")
popped = animals.pop()
print("After modifications:", animals)
print("Popped element:", popped)--OUTPUT--After modifications: {'cat', 'dog'}
Popped element: fish
When you need to remove items from a set, Python provides a few options. The main difference lies in how they handle elements that don't exist. The remove() method is direct; it deletes a specific item like "bird". If the item isn't in the set, it will raise an error.
- For a more forgiving approach, use
discard(). It tried to remove"elephant", but since it wasn't there, the code continued without any issues. - Finally,
pop()removes and returns an arbitrary element. Because sets are unordered, you can't predict which item will be popped.
Advanced set techniques and operations
Once you're comfortable creating and modifying sets, you can leverage more sophisticated features, including set comprehensions, the immutable frozenset, and powerful built-in operators.
Using set comprehensions
squares = {x**2 for x in range(1, 6)}
even_squares = {x**2 for x in range(1, 11) if x % 2 == 0}
print("Squares:", squares)
print("Even squares:", even_squares)--OUTPUT--Squares: {1, 4, 9, 16, 25}
Even squares: {4, 16, 36, 64, 100}
Set comprehensions offer a concise and readable way to create sets from iterables. They're similar to list comprehensions but use curly braces {}. The squares set, for example, is built by applying the expression x**2 to each number in the specified range.
- The basic syntax is
{expression for item in iterable}. - You can also add a conditional filter. The
even_squaresexample uses anifclause to ensure only the squares of even numbers are included in the final set, making comprehensions a powerful tool for data transformation.
Working with immutable frozenset
regular_set = {"a", "b", "c"}
frozen = frozenset(regular_set)
print(frozen)
fs1 = frozenset([1, 2, 3])
fs2 = frozenset([3, 4, 5])
print(fs1.intersection(fs2))--OUTPUT--frozenset({'c', 'b', 'a'})
frozenset({3})
A frozenset is an immutable version of a regular Python set. Once you create one, you can't change its contents with methods like add() or remove(). This immutability is its key feature and its main advantage.
- Because a
frozensetis unchangeable, it's "hashable." This means you can use it as a key in a dictionary or as an element inside another set—something you can't do with a mutableset. - You can still perform standard set operations. As shown with
fs1.intersection(fs2), these methods work just fine, but they return a newfrozensetrather than modifying the originals.
Set operations with operators
set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}
print("Union:", set_a | set_b)
print("Intersection:", set_a & set_b)
print("Difference (A-B):", set_a - set_b)
print("Symmetric difference:", set_a ^ set_b)--OUTPUT--Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Difference (A-B): {1, 2, 3}
Symmetric difference: {1, 2, 3, 6, 7, 8}
Python offers intuitive operators for common set operations, making your code more readable than using method calls. These operators let you combine, compare, and filter sets with familiar mathematical symbols.
- The union operator (
|) merges two sets, discarding any duplicates. - Intersection (
&) finds the elements thatset_aandset_bhave in common. - Difference (
-) returns elements that are in the first set but not the second. - Symmetric difference (
^) gives you all the elements that are in one set or the other—but not in both.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
For the set techniques we've explored, Replit Agent can turn them into production-ready tools:
- Build a content filtering tool that uses set intersection (
&) to find articles that match multiple user-selected tags. - Create an access control dashboard that uses set difference (
-) to show which permissions one user has that another group lacks. - Deploy a data ingestion pipeline that leverages the
set()constructor to automatically deduplicate incoming records in real time.
Describe your app idea, and Replit Agent writes the code, tests it, and handles deployment automatically. Try Replit Agent to turn your concepts into working applications.
Common errors and challenges
Mastering sets means knowing how to navigate common errors, from tricky runtime issues to simple indexing mistakes.
You'll hit a RuntimeError if you try to add or remove elements from a set while iterating directly over it. This happens because changing the set's size mid-loop confuses Python's iterator, which is trying to keep track of its position.
- To get around this, always iterate over a copy. By using the
copy()method, you can loop through a stable version of the set while safely modifying the original.
A TypeError often appears when you attempt to add an "unhashable" item—like a list or another regular set—into a set. Elements in a set must be immutable (unchangeable) so Python can reliably track them.
- Since lists can be modified, they can't be used as set elements. The fix is to convert the item to an immutable type first, such as turning a list into a tuple before adding it.
It's a common mistake to try accessing set elements with an index, as you would with a list. This won't work because sets are fundamentally unordered collections; there's no concept of a "first" or "second" item.
- An expression like
my_set[0]is meaningless in this context. If you need to retrieve an element by its position, you should first convert the set into a list.
Avoiding RuntimeError when modifying a set during iteration
It’s a classic mistake to modify a set while looping over it. Trying to use remove() on an element inside a for loop that iterates over the same set will crash your program with a RuntimeError. The code below shows exactly how this happens.
numbers = {1, 2, 3, 4, 5}
for num in numbers:
if num % 2 == 0:
numbers.remove(num) # This causes RuntimeError
print(numbers)
Here, the for loop is reading from the numbers set at the same time the remove() method is trying to alter it. This conflict is what triggers the RuntimeError. The fix involves a simple change to the loop.
numbers = {1, 2, 3, 4, 5}
numbers_to_remove = {num for num in numbers if num % 2 == 0}
numbers -= numbers_to_remove
print(numbers)
The solution works by separating the two steps. First, you create a new set, numbers_to_remove, using a comprehension to identify the even numbers. Then, you use the set difference operator (-=) to remove all identified items at once. This two-stage process avoids the RuntimeError by never modifying the set while it's being iterated over. You'll need this approach anytime you filter a set based on its own contents.
Handling unhashable types in sets with TypeError
You'll get a TypeError if you try adding a mutable item, like a list, to a set. Because sets require their elements to be immutable—or unchangeable—they can't contain items whose values might be altered later. The following code triggers this error.
my_set = {1, 2, 3}
my_set.add([4, 5, 6]) # Lists are unhashable - TypeError
print(my_set)
The add() method fails because the list [4, 5, 6] is mutable. Sets can only store immutable items, which is why Python raises a TypeError. The following code demonstrates how to correctly add this data.
my_set = {1, 2, 3}
my_set.update([4, 5, 6]) # update() adds individual elements
print(my_set)
The solution is to use the update() method. It works because it doesn't try to add the list as a single, unhashable item. Instead, update() unpacks the iterable and adds each element individually to the set.
- This is why the integers
4,5, and6are successfully added from the list. - You'll run into this
TypeErroranytime you useadd()with a mutable collection, like a list or another set.
Remembering that sets can't be accessed with index notation
Remembering that sets can't be accessed with index notation
It's a common habit from working with lists to try accessing set elements with an index, like fruits[0]. Because sets are unordered, this concept doesn't apply and will always result in a TypeError. The code below shows this common mistake in action.
fruits = {"apple", "banana", "cherry"}
print(fruits[0]) # TypeError: 'set' object is not subscriptable
The error occurs because the square bracket notation [0] is used to access items by position, which sets don't have. This "subscriptable" access triggers the TypeError. The code below demonstrates the correct approach to retrieve an element.
fruits = {"apple", "banana", "cherry"}
fruits_list = list(fruits)
print(fruits_list[0]) # Convert to list for indexing
The fix is to convert the set into a list, which is an ordered collection that supports indexing. By creating fruits_list = list(fruits), you can then access elements by position, such as fruits_list[0].
- This is the standard approach whenever you need positional access to a set's elements.
- Just remember that since the original set was unordered, the order of elements in the new list will be arbitrary.
Real-world applications
With the mechanics of set operations covered, you can now see how they solve problems in text processing and social network analysis.
Finding unique words in text processing
Sets provide a highly efficient way to analyze text by instantly identifying the unique words in a sentence or document.
text = "to be or not to be that is the question"
words = text.split()
unique_words = set(words)
print("Original text:", text)
print("Unique words:", unique_words)
print(f"Word count: {len(words)}, Unique word count: {len(unique_words)}")
The code first uses the split() method to break the sentence into a list of individual words. By passing this list to the set() constructor, you create unique_words, which automatically discards all duplicates.
- Notice how words like "to" and "be" appear only once in the final set.
- The output compares the total word count from the original list to the unique word count from the set, highlighting how efficiently sets handle deduplication in text analysis.
Finding common friends with intersection() in social networks
Set operations are incredibly useful for social network analysis, where finding mutual friends is a common task. By treating each user's friend list as a set, you can use intersection() to see who they know in common. Similarly, set difference (-) can show friends unique to one user, while union (|) can compile a complete list of all distinct friends.
user1_friends = {"Alice", "Bob", "Charlie", "David", "Eve"}
user2_friends = {"Bob", "Charlie", "Frank", "Grace", "Heidi"}
common_friends = user1_friends.intersection(user2_friends)
unique_to_user1 = user1_friends - user2_friends
print(f"Common friends: {common_friends}")
print(f"Friends unique to User 1: {unique_to_user1}")
print(f"Total unique friends: {user1_friends | user2_friends}")
This code demonstrates how set operations produce different views from the same data. After defining two friend lists, it uses three key operations to generate new sets based on their relationship.
- The call to
user1_friends.intersection(user2_friends)returns a new set containing only the names found in both original sets. - The expression
user1_friends - user2_friendscalculates a set of friends that are exclusive to the first user. - Finally, the
user1_friends | user2_friendsexpression merges both lists into a single set with all unique names.
Get started with Replit
Turn what you've learned into a real tool with Replit Agent. Describe what you want, like “a tool that compares two lists of tags and shows the overlap” or “an app that finds all unique words in a document.”
Replit Agent writes the code, tests for errors, and deploys your app automatically. Start building with Replit and bring your ideas to life.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.



