Introduction to Sets in Python
Nimo Mohamed
Posted on August 19, 2023
Data structures are used to organize data for efficient access when needed.
They are a vital part of programming languages and in Python they include: lists, dictionaries,sets and tuples. This article provides a brief overview of the set data structure.
What are Sets?
- These are unordered collections with no duplicate elements, they can be created using curly braces ({}) or the set() function.
- Creating empty sets is only possible through the set() function, as the {} will create an empty dictionary, which is a different data structure altogether.
- Sets are mutable and therefore elements can be added or removed.
- Sets are used for membership testing i.e., checking whether a specific element is present in the sequence, elimination of duplicate entries as well as mathematical operations.
Creation of a set
- Using set() function
>>> a = set((1, 2, 3))
>>> a
{1, 2, 3}
- Using curly braces
>>> my_set = {'Red', 'Yellow', 'Blue'}
>>> type(my_set)
<class 'set'>
Modifying a set
The mutability of sets allows for the addition or removal of elements within a set, this is demonstrated below.
- Adding elements
>>> my_set = {1, 2, 3, 4, 5, 6}
>>> my_set.update((67,))
>>> my_set
{1, 2, 3, 4, 5, 6, 67}
- Removing elements
>>> my_set = {1, 2, 3, 4, 5, 6}
>>> my_set.remove((5))
>>> my_set
{1, 2, 3, 4, 6}
Mathematical operations in sets
- Union: set of all the elements of both sets, without duplicates, uses the ‘|’ operator or the union() method
>>> a = {1, 2, 3, 4, 5, 6,}
>>> b = {9, 10 ,1, 11, 4}
>>> a | b
{1, 2, 3, 4, 5, 6, 9, 10, 11}
>>> a.union(b)
{1, 2, 3, 4, 5, 6, 9, 10, 11}
- Intersection: set of all common elements of both the sets, uses the ‘&’ operator or the intersection() method
>>> a = {1, 2, 3, 4, 5, 6,}
>>> b = {9, 10 ,1, 11, 4}
>>> a & b
{1, 4}
>>> a.intersection(b)
{1, 4}
- Difference: set of all elements in the first set that are not present in the second set, uses the ‘-’ operator or the difference() method
>>> a = {1, 2, 3, 4, 5, 6,}
>>> b = {9, 10 ,1, 11, 4}
>>> a - b
{2, 3, 5, 6}
>>> a.difference(b)
{2, 3, 5, 6}
- Symmetric difference: set of all elements that are either in the first set or the second set, but not in both, uses the ‘^’ operator or the symmetric_difference() method
>>> a = {1, 2, 3, 4, 5, 6,}
>>> b = {9, 10 ,1, 11, 4}
>>> a ^ b
{2, 3, 5, 6, 9, 10, 11}
>>> a.symmetric_difference(b)
{2, 3, 5, 6, 9, 10, 11}
References
💖 💪 🙅 🚩
Nimo Mohamed
Posted on August 19, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.