This tutorial will explain what sets are in Python, why you would use them, and how to carry out various operations with them.
What is Set in Python?
A set is a collection of elements that can be iterated over, changed, and does not contain duplicate elements or an index. Sets let you store multiple items in a single variable.
Sets are one of the four built-in data types in Python, along with Lists, Tuples, and Dictionaries. Each data type has different uses and qualities.
Why use Python Sets?
Python sets are useful because they cannot contain duplicate values, making them ideal for eliminating duplicates in lists or tuples, and for performing common math operations like unions and intersections.
Creating a Set in Python
A set can be created by placing elements inside curly braces {}
and separating them with a comma (,
), or by using the built-in set()
function. Creating an empty set can be done by using empty curly braces.
Example:
x = {}
y = set(['Python', 'is', 'Fun'])
print(x)
print(y)
Output:
{}
{'Fun', 'Python', 'is'}
Note: Set is an unordered collection of items that is iterable. If you run your code again the list will change positions.
To test your Python code from this lesson, use a code editor like PyCharm. You can also test your code online using our free Online Compiler in Python.
Initialize a Set in Python
You can initialize a set in Python by using set() or putting all of the items (elements) inside curly braces {} and putting a comma between each one.
Example:
# using the Set function
set1 = set(['India', 'Philippines'])
print(set1, 'and the following type is', type(set1))
# using curly braces {}
set1 = {'Hello', 'Hey', 'Hi'}
print(set1, 'and the following type is', type(set1))
Output:
{'Philippines', 'India'} and the following type is <class 'set'>
{'Hello', 'Hi', 'Hey'} and the following type is <class 'set'>
Modifying a set in Python
To modify a set in Python, you can use the add()
method to add one element at a time, or the update()
method to add several elements at once. The update()
method can be used with tuples, lists, strings, or other sets.
Example:
# initialize set1
set1 = {1, 3}
print(set1)
# add an element
set1.add(2)
print(set1)
# add multiple elements
set1.update([2, 3, 4])
print(set1)
# add list and set
set1.update([4, 5], {1, 6, 7})
print(set1)
# x = {[1,2,3]:'Error will occur'}
# print(x)
# if you uncomment the code above you will get an error
# Traceback (most recent call last): File "main.py", line 1, in <module>
# TypeError: unhashable type: 'list'
Output:
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 7}
Removing Elements from a Set
Use the remove() or discard() method to remove elements from a set.
The discard()
function does nothing if an element is not in a set, while the remove()
function will throw an error if the element is not present.
Example:
set1 = {'Prince', 'Adones', 'Jude', 'Paul', 'Ted', 'Glen', 'Jaymar'}
set1.discard('Adones')
print('using discard',set1) # discard an element
set1.remove('Ted')
print('using remove',set1) # remove an element
set1.discard('George')
print('discarding an element that is not present in set1',set1) # discard an element not present in set1
set1.remove('George') # remove an element not present in set1, you will get an error.
Output:
using discard {'Paul', 'Ted', 'Jaymar', 'Prince', 'Glen', 'Jude'} using remove {'Paul', 'Jaymar', 'Prince', 'Glen', 'Jude'} discarding an element that is not present in set1 {'Paul', 'Jaymar', 'Prince', 'Glen', 'Jude'} Traceback (most recent call last): File "main.py", line 12, in <module> set1.remove('George') # remove an element not present in set1, you will get an error. KeyError: 'George'
We can remove an item from a set using the pop()
method. Since sets are unordered, we can’t predict which item will be removed. We can also clear a set of all its items using the clear()
method.
Example:
set1 = {'Prince', 'Adones', 'Jude', 'Paul', 'Ted', 'Glen', 'Jaymar'}
print(set1.pop()) # pop an random element
# clear set1
set1.clear()
print('After clearing:',set1) # this will empty the set
Output:
Jaymar
After clearing: set()
Python Set Operations
Python sets can be operated on using union, intersection, difference, and symmetric difference. These operations can be performed using either operators or methods.
A = {1, 2, 3, 4, 5}
B = {5, 6, 7, 8, 9}
The list below shows the description of Python Set Operations and their diagrams with examples:
Set Union
Set Union – is a set that has all the elements from both sets.
The |
operator and the union()
method are used to make a union.
Set Intersection
Set Intersection – is a set of elements that are in both A and B.
The &
operator and the intersection()
method are used to make an intersection.
Set Difference
Set Difference – is a set of elements that are only in set A and not in set B. In the same way, B – A is a set of elements that are in B but not in A.
The -
operator and the difference()
method are used to make a difference.
Set Symmetric Difference
Set Symmetric Difference – is a set of elements in A and B that aren’t in B. (excluding the intersection).
The ^
operator and the symmetric_difference()
method are used to make an symmetric difference.
Python Set Functions
In the table below, you’ll find a list of Python Set Functions that are commonly used with sets to do different tasks.
Function | Description |
---|---|
all() | Returns True if all elements of the set are true (or if the set is empty). |
any() | Returns True if any element of the set is true. If the set is empty, returns False . |
enumerate() | Returns an enumerate object. It contains the index and value for all the items of the set as a pair. |
len() | Returns the length (the number of items) in the set. |
max() | Returns the largest item in the set. |
min() | Returns the smallest item in the set. |
sorted() | Returns a new sorted list from elements in the set(does not sort the set itself). |
sum() | Returns the sum of all elements in the set. |
Python Set Methods
Python has many Set Methods and we’ve already talked about some of them. Here is a list of all the ways that set objects can be used:
Methods | Description |
---|---|
add() | Adds an element to the set |
clear() | Removes all elements from the set |
copy() | Returns a copy of the set |
difference() | Returns the difference of two or more sets as a new set |
difference_update() | Removes all elements of another set from this set |
discard() | Removes an element from the set if it is a member. (Do nothing if the element is not in set) |
intersection() | Returns the intersection of two sets as a new set |
intersection_update() | Updates the set with the intersection of itself and another |
isdisjoint() | Returns True if two sets have a null intersection |
issubset() | Returns True if another set contains this set |
issuperset() | Returns True if this set contains another set |
pop() | Removes and returns an arbitrary set element. Raises KeyError if the set is empty |
remove() | Removes an element from the set. If the element is not a member, raises a KeyError |
symmetric_difference() | Returns the symmetric difference of two sets as a new set |
symmetric_difference_update() | Updates a set with the symmetric difference of itself and another |
union() | Returns the union of sets in a new set |
update() | Updates the set with the union of itself and others |
Summary
In this tutorial, you have learned about the set data type in Python. This includes what sets are, and why you would use them. You have also seen some examples of set operations.
I hope this lesson has helped you understand what is a set in Python and its uses. If you missed any of our previous lessons, check out our list of Python tutorial for absolute beginners.
In the next post, you’ll learn about Python Dictionaries, including their properties, built-in functions, and how to use them correctly.
Python Tuples
Python Dictionaries