What are sets in Python?

Sets are an unordered collection of unique elements. They used to store multiple items in a variable, making it easier to manage groups of data. Sets are mutable, which means we can add or remove items after creation. The items of a set must be immutable (like numbers, strings, or tuples).

Sets in Python

Assume you're organizing a guest list for a party. You start adding friends, but before you know it, you've accidentally written down the same friend's name twice! With a regular list, duplicates like this can happen easily. But with a set, Python ensures that each friend is invited only once, no matter how many times you add their name! This unique quality makes sets in Python a powerful tool for managing collections of data, where each item is distinct and order doesn’t matter.

This answer will cover how sets work, including creating sets, adding and removing elements, and performing various operations like union and intersection. Whether you're cleaning up data or simplifying data comparisons, sets are a useful addition to your Python toolkit. Let's move on to the next step!

Create a set in Python

To create a set, we have two options:

  1. Curly braces {}

  2. set() function

# Using curly braces
my_set = {1, 2, 3, 4}
# Using the set() function
my_set_from_function = set([1, 2, 3, 4])
print(my_set) # Output: {1, 2, 3, 4}

Add and remove values from sets

Let's see each example of how we can add and remove elements from the sets below:

1. Add elements

To add values to sets in Python, the add() method is used. This method allows us to insert a single item into a set without adding duplicates. Since sets are unique by nature, any attempt to add a value already in the set will have no effect.

my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}

Try experimenting with all the codes. In the above example, consider adding a duplicate, like my_set.add(3), and run the code to see how it behaves with duplicate elements.

2. Remove elements

To remove elements from a set, we can use the remove() method, which raises an error if the item does not exist, or discard(), which quietly does nothing if the item is absent. This flexibility makes managing content in sets easy and safe.

my_set = {1, 2, 3, 4}
# Using remove()
my_set.remove(2)
print(my_set) # Output: {1, 3, 4}
# Using discard()
my_set.discard(5) # Does not raise an error

3. Remove all elements

If we need to clear all the elements from a set, we can call the clear() method. This effectively empties the set, making it useful when we want to reuse the same variable without needing to create a new set.

my_set = {1, 2, 3}
my_set.clear()
print(my_set) # Output: set()

Iteration in sets

Iterating through a set in Python can be done using a simple for loop. Since sets do not maintain any particular order, the output may vary on different executions. This iteration allows us to access each unique element stored in the set without duplicates.

my_set = {1, 3, 3, 2}
for item in my_set:
print(item)
# Output: 1 2 3 (order may vary)

Sort set

Sets are unordered, we can convert them into a list of ordered values using the sorted() function. This is helpful when you need to present the data in a specific sequence, allowing us to enjoy the benefits of sets while also displaying the data in an ordered manner.

my_set = {3, 1, 2}
ordered_list = sorted(my_set)
print(ordered_list) # Output: [1, 2, 3]

Remove duplicates

Sets in Python are ideal for removing duplicates from lists. By converting a list to a set, we automatically filter out any repeated elements, providing a clean list of unique items. This is particularly useful when we want to ensure that the data we’re working with is distinct.

my_list = [1, 2, 2, 3, 4, 4]
unique_list = list(set(my_list))
print(unique_list) # Output: [1, 2, 3, 4]

Python set operations

Sets in Python are used to perform common mathematical operations like union, intersection, difference, and symmetric difference. These operations help in comparing sets, finding commonalities, and excluding specific values. We can use methods like union(), intersection(), difference(), and symmetric_difference() to execute these operations.

Operation

Description

Method

Operator

Example

Union

Combines elements of both sets, without duplicates.

A.union(B)

A | B

{1, 2, 3} & {2, 3, 4} = {1, 2, 3, 4}

Intersection

Returns common elements found in both sets.

A.intersection(B)

A & B

{1, 2, 3} & {2, 3, 4} = {2, 3}

Difference

Returns elements present in the first set but not in the second.

A.difference(B)

A - B

{1, 2, 3} - {2, 3} = {1}

Symmetric Difference

Returns elements in either set but not in both.

A.symmetric_difference(B)

A ^ B

{1, 2, 3} ^ {2, 3, 4} = {1, 4}

Sets activity

Test all the sets operation by uncommenting the lines 4–6 below:

set_A = {3, 1, 2}
set_B = {3, 4, 5}
# Test all the sets methods by uncommenting
# print(set_A.union(set_B))
# print(set_A.intersection(set_B))
# print(set_A.difference(set_B))
# print(set_A.symmetric_difference(set_B))

Key Takeaways:

  • Definition and characteristics: Sets in Python are unordered collections of unique, immutable elements. They allow efficient storage and management of data without duplicates.

  • Creating sets: Sets can be created using curly braces {} or the set() function, which enables flexibility in initializing sets from different iterables like lists or tuples.

  • Adding and removing elements: Use the add() method to insert elements into a set, and remove() or discard() to delete them. The clear() method removes all elements from the set.

  • Iterating and sorting: Iterate through sets using a for loop, and use sorted() to convert the set into a sorted list.

  • Removing duplicates: Convert lists to sets to automatically filter out duplicate elements, providing a clean list of unique items.

  • Set operations: Perform common mathematical operations like union, intersection, difference, and symmetric difference using set methods or operators for effective set comparisons and manipulations.

Ready to deepen your Python knowledge? Start our Become a Python Developer path, beginning with Python's basic concepts and advancing to more complex topics, preparing you for a career as a Python developer.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What are sets in Python?

Sets in Python are unordered collections of unique elements. They are used to store multiple distinct items in a single variable, offering efficient methods for managing and comparing data.


What is a set define type in Python?

A set in Python is a mutable, unordered collection of unique, immutable elements. It is defined using curly braces {} or the set() function and does not allow duplicate values.


What is set and tuple in Python?

A set is a collection of unique elements, while a tuple is an ordered, immutable sequence of elements. Sets support mathematical operations like union and intersection, whereas tuples maintain the order and are used for fixed collections of items.


What are the set operators in Python?

Set operators include | (union), & (intersection), - (difference), and ^ (symmetric difference). These operators enable efficient comparisons and mathematical operations on sets.


What happens if you try to access a set element by index?

In Python, you can’t access set elements by index because sets are unordered collections. Attempting to do so will raise a TypeError.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved