Python sets are a singular and important data type, which is useful in many different programming tasks. Sets store several items under one variable like lists and dictionaries. However, these sets are not arranged according to any order. Hence, the elements don’t appear in any particular order and they do not allow duplicate values. This makes them very useful for applications like membership testing, and removal of duplicates including mathematical operations such as union and intersection.
This blog will cover everything about Python sets you should know. We will begin with the basics such as what’s a set and its characteristics then we shall delve into set operations, and methods and even expose some mathematical operations with examples given.
What is a Set?
A set in Python is a collection of unordered, unique items. Unlike lists or tuples, sets do not allow duplicate elements. This means that each item in a set is unique, making sets ideal for storing distinct values and performing membership tests.
Sets are defined using curly braces {} or the set() function. For example, {1, 2, 3} is a set containing the numbers 1, 2, and 3. You can also create an empty set using set(), but not {}, as the latter will create an empty dictionary. Sets are mutable, so you can add or remove items after creating them. However, the items themselves must be immutable, like numbers, strings, or tuples.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Characteristics of the Python Sets
Here are some features of Python sets that we have discussed here in brief.
Unordered: The sequence is not maintained inside a set. Elements can occur in random ways.
Unique Elements: There are no repeated values among the elements enclosed within a set.
Mutable: After instantiation, it is possible to change a set e.g., add or remove elements from it.
Immutable Elements: Only immutable objects can be included inside sets e.g., numbers, strings, or tuples but excluding lists or dictionaries.
Heterogeneous Elements: A collection may include members from different data types such as integers, strings, etc.
Dynamic Size: There is an increase or decrease in size depending on whether elements are added to it or removed from there respectively.
No Indexing or Slicing: Unordered sequences cannot be indexed, sliced, etc. by these structures unless using other set functions like the disjoint method or other sequence-like behaviour.
Efficient Membership Testing: The most efficient way to check if an element is present is using the ‘’in’’ operator.
Python provides various operations to work with sets. These operations include creating sets, adding elements, checking for element presence, and more.
Creating a Set
You can create a set in Python using curly braces {} or the set() constructor. Creating a set with curly braces is straightforward and allows you to define the elements directly.
Example:
In the below example, my_set is created using curly braces and contains the elements 1, 2, and 3. The print() function displays the set.
# Creating a set using curly braces
my_set = {1, 2, 3}
print(my_set)
Output:
{1, 2, 3}
Set() Constructor
The set() constructor can be used to create a set from any iterable, such as a list, string, or tuple. This method is useful when you want to convert another data type into a set.
Example from a list:
Here, list_set is created from a list [1, 2, 3, 4] using the set() constructor. The print() function displays the set, showing the unique elements.
# Creating a set from a list
list_set = set([1, 2, 3, 4])
print(list_set)
Output:
{1, 2, 3, 4}
Example from a string:
In this example, string_set is created from the string “hello”. The set() constructor converts the string into a set of unique characters. The print() function shows the unique characters in the set.
# Creating a set from a string
string_set = set("hello")
print(string_set)
Output:
{'e', 'h', 'l', 'o'}
Example of creating an empty set:
Creating an empty set requires using the set() constructor, as using {} will create an empty dictionary.
In this example, empty_set is created using the set() constructor, resulting in an empty set. The print() function confirms this by displaying set().
# Creating an empty set using the set() constructor
empty_set = set()
print(empty_set)
Output:
set()
Adding Elements into the Set
You can add elements to a set using the add() method for single elements or the update() method for multiple elements. These methods allow you to modify the set after its creation.
Example
In this example, the add() method adds the element 4 to my_set. The print() function displays the updated set, which now includes the new element.
# Adding a single element
my_set = {1, 2, 3}
my_set.add(4)
print(my_set)
Output:
{1, 2, 3, 4}
Example
In this example, the update() method adds the elements 4, 5, and 6 to my_set. The print() function displays the updated set with the new elements included.
You can check if an element exists in a set using the ‘in’ keyword. This operation returns True if the element is present and False if it is not.
Example
In this example, the in keyword checks if the element 2 is in my_set, returning True. It also checks if the element 5 is in my_set, returning False since 5 is not present in the set.
my_set = {1, 2, 3, 4}
print(2 in my_set)
print(5 in my_set)
Output:
True
False
Removing Elements from the Set
You can remove elements from a set using the remove(), discard(), or pop() methods. Each method has its unique behaviour.
Using remove()
The remove() method removes a specified element from the set. If the element is not found, it raises a KeyError.
Example
In this example, the remove() method removes the element 3 from my_set. If you try to remove an element that does not exist, it will raise a KeyError.
my_set = {1, 2, 3, 4}
my_set.remove(3)
print(my_set)
# Trying to remove an element not present in the set
# my_set.remove(5) # Raises KeyError
Output:
{1, 2, 4}
Using discard()
The discard() method also removes a specified element from the set, but it does not raise an error if the element is not found.
Example:
In this example, the discard() method removes the element 3 from my_set. Unlike remove(), it does not raise an error when trying to discard an element that is not in the set.
my_set = {1, 2, 3, 4}
my_set.discard(3)
print(my_set)
# Trying to discard an element not present in the set
my_set.discard(5) # No error
print(my_set)
Output:
{1, 2, 4}
{1, 2, 4}
Using pop()
The pop() method removes and returns an arbitrary element from the set. If the set is empty, it raises a KeyError.
Example:
In this example, the pop() method removes and returns an arbitrary element from my_set. The print() function shows the removed element and the updated set.
my_set = {1, 2, 3, 4}
removed_element = my_set.pop()
print(removed_element) # Output: (any element from the set, e.g., 1)
print(my_set) # Output: Remaining elements in the set, e.g., {2, 3, 4}
Output:
1
{2, 3,4}
Internal Working of the Set
Sets in Python are implemented using hash tables. This allows for fast membership testing and insertion/deletion operations. Each element in a set must be hashable, which means it must have a hash value that does not change during its lifetime.
When you add an element to a set, Python computes the hash of the element and uses this value to determine where to place the element in the internal hash table. This makes checking for membership (using the in keyword) very efficient, with an average time complexity of O(1).
Find the Length of the Set
You can find the number of elements in a set using the len() function.
Example:
In this example, the len() function returns the number of elements in my_set, which is 4.
my_set = {1, 2, 3, 4}
print(len(my_set))
Output:
4
Looping a Set
You can loop through the elements of a set using a for loop. Since sets are unordered, the elements will be iterated in an arbitrary order.
Example:
In this example, the for loop iterates over each element in my_set, printing them one by one.
my_set = {1, 2, 3, 4}
for element in my_set:
print(element)
# Output: Elements in any order, e.g., 1 2 3 4
Output:
1 2 3 4
Set Comparison
You can compare sets in Python using various comparison operators. These operators allow you to check for equality, inequality, and subset/superset relationships. Here is a table of the common comparison operators and their descriptions:
Operator
Description
==
Checks if two sets are equal
!=
Checks if two sets are not equal
<
Checks if the left set is a subset of the right set
<=
Checks if the left set is a subset of the right set or equal to it
>
Checks if the left set is a superset of the right set
>=
Checks if the left set is a superset of the right set or equal to it
Let’s see how these operators work with examples.
Example of Equality (== and !=):
The == operator checks if two sets have the same elements, while the != operator checks if they do not.
In this example, set1 and set2 are equal because they contain the same elements, while set1 and set3 are not equal.
The < operator checks if the left set is a proper subset of the right set. The <= operator checks if the left set is a subset of the right set or equal to it. Similarly, the > operator checks if the left set is a proper superset of the right set, and the >= operator checks if the left set is a superset of the right set or equal to it.
set1 = {1, 2, 3}
set3 = {1, 2}
set4 = {1, 2, 3, 4}
# Subset and Superset
print(set3 < set1) # Output: True (set3 is a proper subset of set1) print(set1 > set3) # Output: True (set1 is a proper superset of set3)
print(set3 <= set1) # Output: True (set3 is a subset of set1) print(set1 >= set3) # Output: True (set1 is a superset of set3)
# Proper Subset and Proper Superset
print(set1 < set4) # Output: True (set1 is a proper subset of set4) print(set4 > set1) # Output: True (set4 is a proper superset of set1)
These comparisons help you understand the relationships between different sets, allowing you to perform various operations and checks effectively.
Mathematical Operations on Set With Examples
Python sets support several mathematical operations, such as union, intersection, difference, and symmetric difference. These operations help you to perform common set operations easily and efficiently.
Union Operation
The union operation combines the elements of two sets into one, excluding duplicates. You can use the union() method or the | operator.
Using union() method:
In this example, union_set contains all elements from both set1 and set2, excluding duplicates.
The symmetric difference operation returns elements that are in either of the sets but not in both. You can use the symmetric_difference() method or the ^ operator.
Using symmetric_difference() method:
In this example, symmetric_difference_set contains elements (1, 2, 4, 5) that are in either set1 or set2 but not in both.
Python sets come with a variety of built-in methods that allow you to perform different operations. These methods make it easy to manipulate and manage sets effectively.
Set Methods
Method
Description
add()
Adds a single element to the set
update()
Adds multiple elements to the set
remove()
Removes a specified element from the set
discard()
Removes a specified element without raising an error
pop()
Removes and returns an arbitrary element from the set
clear()
Removes all elements from the set
copy()
Returns a shallow copy of the set
union()
Returns the union of sets
intersection()
Returns the intersection of sets
difference()
Returns the difference of sets
symmetric_difference()
Returns the symmetric difference of sets
issubset()
Checks if the set is a subset of another set
issuperset()
Check if the set is a superset of another set
isdisjoint()
Checks if two sets have no elements in common
Let’s look at examples for a few of these methods to understand how they work.
Example of clear():
The clear() method removes all elements from the set, leaving it empty.
Here, the copy() method creates a shallow copy of my_set and assigns it to copy_set. The print() function displays the copied set, which contains the same elements as my_set.
A frozen set is a type of set that is immutable, meaning once it is created, you cannot change its elements. Frozen sets are similar to regular sets but with the restriction that they cannot be modified after creation. This immutability makes frozen sets hashable, allowing them to be used as keys in dictionaries or elements of other sets.
You can create a frozen set using the frozenset() function.
Example 1: Creating a Frozen Set
You can create a frozen set from any iterable, such as a list or a string.
In this example, frozenset([1, 2, 3, 4]) creates a frozen set from a list, and frozenset(“hello”) creates a frozen set from a string. The print() function displays the elements of the frozen sets.
# Creating a frozen set from a list
frozen_set = frozenset([1, 2, 3, 4])
print(frozen_set) # Output: frozenset({1, 2, 3, 4})
# Creating a frozen set from a string
frozen_set_string = frozenset("hello")
print(frozen_set_string) # Output: frozenset({'h', 'e', 'l', 'o'})
Example 2: Using Frozen Set as Dictionary Keys
Since frozen sets are immutable and hashable, they can be used as keys in a dictionary.
In this example, frozen_set1 and frozen_set2 are used as keys in the dictionary my_dict. The print() function shows the dictionary with frozen sets as keys, each associated with a corresponding value.
Frozen sets provide a way to use sets in contexts where immutability is required, such as dictionary keys or elements of other sets.
Python Set Problems With Solutions
Python sets are versatile and can solve various problems efficiently. Here are some common problems and their solutions using sets.
Finding Minimum and Maximum in the Set
You can find the minimum and maximum values in a set using the min() and max() functions.
Example:
In this example, min(my_set) finds the smallest element in my_set, which is 1, and max(my_set) finds the largest element, which is 9. The print() function displays these values.
You can remove multiple elements from a set using the difference_update() method or a loop.
Using difference_update() method:
In this example, difference_update(elements_to_remove) removes the elements 2 and 3 from my_set. The print() function shows the updated set without these elements.
You can add multiple elements to a set using the update() method.
Example:
In this example, update(elements_to_add) adds the elements 4, 5, and 6 to my_set. The print() function shows the updated set with the new elements included.
These examples demonstrate how to solve common problems using Python sets, making your code more efficient and concise.
Conclusion
Python sets are powerful tools for handling collections of unique items. They provide efficient ways to perform membership testing, eliminate duplicates, and carry out mathematical operations. By understanding the basics of sets, their characteristics, and various operations, you can effectively use sets in your Python projects to solve complex problems with ease.
From creating sets to performing union, intersection, and difference operations, this guide has covered everything you need to know about Python sets. Equipped with this knowledge, you can enhance your programming skills and handle data more efficiently in your applications.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.