Python Sets
Python Sets
In Python, a set is an unordered collection of unique elements. Unlike lists or tuples, sets do not
allow duplicate values i.e. each element in a set must be unique. Sets are mutable, meaning you
can add or remove items after a set has been created.
Sets are defined using curly braces {} or the built-in set() function. They are particularly useful for
membership testing, removing duplicates from a sequence, and performing common mathematical
set operations like union, intersection, and difference.
A set refers to a collection of distinct objects. It is used to group objects together and to study their
properties and relationships. The objects in a set are called elements or members of the set.
Creating a set in Python refers to defining and initializing a collection of unique elements. This
includes specifying the elements that will be part of the set, ensuring that each element is unique
within the set.
You can create a set in Python using curly braces {} or the set() function −
You can directly define a set by listing its elements within curly braces, separating each element
by a comma as shown below −
my_set = {1, 2, 3, 4, 5}
print (my_set)
{1, 2, 3, 4, 5}
Alternatively, you can create a set using the set() function by passing an iterable (like a list or a
tuple) containing the elements you want to include in the set −
my_set = set([1, 2, 3, 4, 5])
print (my_set)
{1, 2, 3, 4, 5}
Sets in Python are unordered collections of unique elements. If you try to create a set with duplicate
elements, duplicates will be automatically removed −
my_set = {1, 2, 2, 3, 3, 4, 5, 5}
print (my_set)
{1, 2, 3, 4, 5}
Sets can contain elements of different data types, including numbers, strings, and even other sets
(as long as they are immutable) −
print (mixed_set)
In Python, sets support various basic operations that is used to manipulate their elements. These
operations include adding and removing elements, checking membership, and performing set-
specific operations like union, intersection, difference, and symmetric difference.
Adding Elements in a Set
To add an element to a set, you can use the add() function. This is useful when you want to include
new elements into an existing set. If the element is already present in the set, the set remains
unchanged −
my_set = {1, 2, 3, 3}
my_set.add(4)
print (my_set)
{1, 2, 3, 4}
You can remove an element from a set using the remove() function. This is useful when you want
to eliminate specific elements from the set. If the element is not present, a KeyError is raised −
my_set = {1, 2, 3, 4}
my_set.remove(3)
print (my_set)
{1, 2, 4}
Alternatively, you can use the discard() function to remove an element from the set if it is present.
Unlike remove(), discard() does not raise an error if the element is not found in the set −
my_set = {1, 2, 3, 4}
print (my_set)
{1, 2, 3, 4}
Sets provide an efficient way to check if an element is present in the set. You can use
the in keyword to perform this check, which returns True if the element is present
and False otherwise −
my_set = {1, 2, 3, 4}
if 2 in my_set:
else:
Set Operations
In Python, sets support various set operations, which is used to manipulate and compare sets. These
operations include union, intersection, difference, symmetric difference, and subset testing. Sets
are particularly useful when dealing with collections of unique elements and performing operations
based on set theory.
Union − It combine elements from both sets using the union() function or the | operator.
Intersection − It is used to get common elements using the intersection() function or
the & operator.
Difference − It is used to get elements that are in one set but not the other using the
difference() function or the - operator.
Symmetric Difference − It is used to get elements that are in either of the sets but not in
both using the symmetric_difference() method or the ^ operator.
Set comprehensions in Python is a concise way to create sets based on iterable objects, similar to
list comprehensions. It is used to generate sets by applying an expression to each item in an
iterable.
Set comprehensions are useful when you need to create a set from the result of applying some
operation or filtering elements from another iterable.
Syntax
The syntax for set comprehensions is similar to list comprehensions, but instead of square brackets
[ ], you use curly braces { } to denote a set −
Example
In the following example, we are creating a set containing the squares of numbers from 1 to 5
using a set comprehension −
print(squared_set)
You can include conditional statements in set comprehensions to filter elements based on certain
criteria. For instance, to create a set of even numbers from 1 to 10, you can use a set comprehension
with an if condition as shown below −
print(even_set)
{2, 4, 6, 8, 10}
Set comprehensions also support nested loops, allowing you to create sets from nested iterables.
This can be useful for generating combinations or permutations of elements.
Example
print(nested_set)
Frozen Sets
In Python, a frozen set is an immutable collection of unique elements, similar to a regular set but
with the distinction that it cannot be modified after creation. Once created, the elements within a
frozen set cannot be added, removed, or modified, making it a suitable choice when you need an
immutable set.
You can create a frozen set in Python using the frozenset() function by passing an iterable (such
as a list, tuple, or another set) containing the elements you want to include in the frozen set.
Example
In the following example, we are creating a frozen set of integers and then adding an element to it
print(my_frozen_set)
my_frozen_set.add(4)
frozenset({1, 2, 3})
my_frozen_set.add(4)