Similar to a list, a set in Python is another data type that contains an unordered collection of unique elements or values.
For example, suppose we want to store information about student roll nos. Since student roll nos cannot be duplicate, we can use a set.
Every element in a set is unique. Therefore, there is no duplication of elements allowed in the set, which makes it similar to the keys of a dictionary.
Python uses hash table data structure to implement uniqueness in a set. A set class in Python represents the mathematical notation of a set. Python supports two types of set classes. They are:
- Set class
- Frozenset class
A set class itself is a mutable object or data type in Python, meaning that we can perform any changes in the existing set object based on need without creating a new set object. In other words, we can add or remove elements in the existing set object after set object creation.
On the other hand, a frozenset class is an immutable in nature, meaning that once we create its contents, we cannot perform any changes in an existing forzenset object.
Since sets are an unordered collection of elements therefore, we cannot access their elements using an index as we do in lists. Indexing and slicing do not work with a set.
We can use sets to store multiple elements in a single variable and test if an element is present in the set or not. Mutable elements such as a dictionary, list, or set cannot be a member of a set.
We can use set to perform all mathematical set operations, such as union, intersection, difference, or symmetric difference.
How to Create a Set in Python
There are two ways to create a set in Python that are as:
1. Using curly braces:
In Python, we can create a set object by enclosing all the elements inside curly braces { }, separated by a comma. The general syntax to create a set in Python is as:
my_set = {element_1, element_2, element_3, . . . . . , element_n} or, my_set = {value1, value2, value3, . . . . ., valuen}
In the above syntax, my_set is the name of a set and value1, value2, . . ., valuen are the values or elements assigned to the set.
Let us take a simple example of creating a numeric set.
Example 1:
# Creating a numeric set. my_set = {2, 4, 6, 8, 10, 12} # Displaying set elements. print(my_set)
Output: {2, 4, 6, 8, 10, 12}
In this example, we have created a set object containing integer values and assigned to it into a variable named my_set. Then, we have displayed it on the console.
Example 2:
# Creating a set of strings. my_set = {"Orange", "Banana", "Mango", "Guava"} print(my_set)
Output: {'Banana', 'Mango', 'Orange', 'Guava'}
Example 3:
# Creating a set of mixed data types. my_set = {25, 20.24, "Python", ("A", "B", "C")} print(my_set)
Output: {('A', 'B', 'C'), 25, 'Python', 20.24}
As you can see in the output, the set does not maintain the insertion order in which we had placed elements.
2. Using set() function:
This is another way of creating a set object in Python using a built-in set() function. Only we need to pass an argument to the set function. Argument can be an element, or an iterable element like list, tuple, or a string. The general syntax to create a set usint set() function is as:
my_set = set({element_1, element_2, . . . . , element_n})
Note that all the elements of a set must be placed inside the set function by placing within curly braces { }, and separated by a comma.
Let’s take some simple example of it.
Example 4:
# Creating a set using set() function and passing a set of elements as an argument. my_set = set({"John", "Bob", "Amit", "Merry"}) print(my_set)
Output: {'Merry', 'John', 'Amit', 'Bob'}
In this example, we have created a set using set() function and passed it a set of elements as an argument. Then, we have displayed it.
Example 5:
# Creating a list object. my_list = [1, 2, 3, 4, 5] # Create a set using set function and pass the list of elements to it. my_set = set(my_list) print(my_set)
Output: {1, 2, 3, 4, 5}
Note that we can pass any sequence of elements to the set() function to construct a set. However, a set will drop duplicate elements.
Example 6:
# Creating a list containing duplicate elements. my_list = [2, 4, 6, 8, 2, 6, 10] # Creating a set without duplicate elements. my_set = set(my_list) print(my_set)
Output: {2, 4, 6, 8, 10}
How to create an Empty Set in Python
To create an empty set, we will use the set() function without any argument. Creating an empty set is not possible using curly braces { } because it is a syntax of creating an empty dictionary.
Example 7:
# Creating am empty set object using set function. empty_set = set() print(type(empty_set)) # Creating a dictionary using curly braces. empty_dict = {} print(type(empty_dict))
Output: <class 'set'> <class 'dict'>
In this example, we have created an empty set using set() function. Then, we have used type() function to know the type of an empty set object which displayed a <class ‘set’>.
Again, we have created an empty set using curly braces { } but it creates a dictionary because when we used type function to know the type of it shows <class ‘dict’>.
Features of Set in Python
There are the following key features of set in Python that you should keep in mind. They are as:
(1) Underlying data structure: The underlying data structure of implementing a uniqueness of a set in Python is a hash table. A hash table is a data structure that stores keys optionally with corresponding values.
(2) Unordered: As a set is an unordered collection of elements or objects, so it does not maintain our insertion order. The order of elements in the set appears in a different order every time. But, we can make it ordered by using sorted() function.
(3) Unique elements: A set data structure can only contain unique elements. Therefore, it does not allow duplicate elements or values.
(4) Mutable nature: A set itself is a mutable object or data type in Python. Therefore, we can easily add, update, and delete elements in the existing set object. Since a set is a mutable object therefore, it does not have hash value. So, we cannot use it as a dictionary key or as an element of different sets.
(5) Speed: Python’s set data structure is optimized for very speedy searching. It searches elements much faster as compared to list. This is because lists always perform the slow sequential searches. Therefore, sets should be preferred when searching is the primary requirement.
(6) Heterogeneous data: One of the biggest advantages of using sets in Python is that we can create sets of heterogeneous elements or data.
In simple words, sets can store elements or data of different data types, such as characters, boolean, string, numbers, employee objects or any tuple object in Python as an element. However, a set in Python cannot store composite data types, such as lists, dictionaries, or other sets.
(7) Functionality: Python sets come with many built-in functions that allow us easily to perform a different set of operations instead of writing long code from scratch. We can use dir(set) to gain a list of functions provided by a set in Python. For example:
# Getting a list of functions provided by set in Python. print(dir(set))
Output: ['__and__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', ' 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
(8) Memory location: Python sets data structure does not store elements in sequential or contiguous memory locations. Like the dictionary, a set creates hash code values for each element using a built-in function named hash(). It uses this calculated hash code value to calculate the location of elements which makes it unordered data structures.
(9) Set operations: Sets in Python support various mathematical operations, such as union, intersection, difference, and symmetric difference.
(10) Membership testing: We can test if an element is present in the set or not by using (in or not in) operators.
How to access Set in Python?
Since a set is an unordered collection of objects in Python, so we cannot access directly using indexing or slicing. If we try to access an element using an index in a set, it will throw TypeError, as shown in the below example.
Example 8:
# Creating a set of mixed data types. my_set = {25, 20.24, "Python"} # Trying to access an element in a set using index. print(my_set[2])
Output: TypeError: 'set' object is not subscriptable
To access a set element, we will have to iterate over set one by one. Iteration over a set means accessing each element of a set one by one and printing each element. Let’s take an example in which we will iterate over a set using for loop in Python.
Example 9:
# Creating a set of mixed data types. my_set = {25, 20.24, "Python", (2, 3, 4, 5)} # Iterating over a set using for loop. for x in my_set: print(x)
Output: 25 20.24 (2, 3, 4, 5) Python
Adding Elements in Sets
Set is a mutable collection of objects; we can easily add new elements in the existing set. However, while adding new elements in the set, it deletes duplicate elements, as the set is a composing of unique elements only. There are two methods by which we can insert new elements in the set. They are as:
(a) set.add(element): We use this method to add a single element in the set.
(b) set.update(element(s)): We use this method to insert multiple elements to the set. This method takes an iterable object like a list or set. Using this method, we can add strings, lists, tuples, or other set as an element.
Let’s take some examples of inserting new elements in the set.
Example 10:
# Python program to add an element to a set. my_set = {2 , 4, 6, 8} # Adding a single element in an existing set. my_set.add(10) print(my_set)
Output: {2, 4, 6, 8, 10}
Note that adding elements to a set may change the order of existing elements in the set.
Example 11:
# Python program to add string elements to a set. my_set = {2 , 4} # Adding multiple strings in an existing set using update() method. my_set.update('a', 'b', 'c') print(my_set)
Output: {2, 4, 'a', 'b', 'c'}
Example 12:
# Python program to add a list elements to a set. my_set = {2 , 4, 6, 8} # Adding an iterable list in an existing set using update() method. my_set.update([6, 8, 10, 12]) print(my_set)
Output: {2, 4, 6, 8, 10, 12}
As you can see in this example, a set ignored duplicate elements when we have added a list of elements to a set.
Example 13:
# Python program to add a string object to a set. my_set = {2, 4} # Adding a string in an existing set using update() method. my_set.update("Testing") print(my_set)
Output: {2, 4, 'T', 'i', 'g', 's', 'n', 'e', 't'}
Note that if an element to be added using update() function is a string, it is considered as an iterable object. Therefore, each character or string is added as an individual element to a set.
Example 14:
# Python program to add integer objects to a set. my_set = {1, 3, 5} # Adding multiple integers in an existing set using update() method. my_set.update(7, 9, 11) print(my_set)
Output: TypeError: 'int' object is not iterable
As you can see in the code, we cannot update integers directly through update() function because the update() function only supports iterable objects like list, tuple, etc.
Deleting or Removing Set Elements
Python set is a mutable collection of elements or data; we can easily delete individual or multiple elements from the set. There are the following methods by which we can remove the set element. They are:
(a) set.remove(element): This method deletes the specified element. It will throw KeyError exception if the specified element does not exist in the set.
(b) set.discard(element): This method removes the specified element from the set. It differs from remove() method as discard() does not throw keyError when the element does not exist in the set.
(c) set.pop(): This method removes a random element from the set and returns the removed element. If the set is empty, then it returns KeyError exception.
(d) set.clear(): This method deletes all the elements from the set.
Let’s take an example to perform deletion operation in the Python sets.
Example 15:
# Python program to delete elements from the set. my_set = {2, 4, 6, 9, 10, 12} # Deleting an element from the set. my_set.remove(9) my_set.add(8) # adding an element. print(my_set) my_set2 = {1, 3, 5, 6, 9} # Deleting an element 6 from the set. my_set2.discard(6) my_set2.add(7) print(my_set2) my_set3 = {"AA", "BB", "CC", "DD"} # This method removes a random element from a set. my_set3.pop() print(my_set3) # Deleting all elements from the set. my_set3.clear() print(my_set3)
Output: {2, 4, 6, 8, 10, 12} {1, 3, 5, 7, 9} {'DD', 'BB', 'CC'} set()
Advantage of Sets in Python
There are the following advantages of using sets in Python. They are as:
- The outstanding advantage of using a set is that it has a highly optimized and effective method for searching whether a particular element is present in the set or not.
- Set allows to remove duplicate elements. It retains only unique elements.
- It allows to store heterogeneous elements.
- As a set is a mutable object in Python, we can easily add, remove, or update elements in the existing set.
- Set allows us to perform various mathematical operations, such as union, intersection, difference, and symmetric difference.
When to use List, Tuple, or Set in Python?
There are three key points by which we can easily understand when to use list, tuple, and set data structures in Python programming. They are:
(a) List: A list is ideal for use when you need an ordered sequence of heterogeneous elements whose values can change later in the program.
(b) Tuple: A tuple is ideal for use when you need an ordered sequence of heterogeneous elements whose values will not change later in the program.
(c) Set: It is ideal for use when you do not want to store duplicate elements as well as also do not want an order of elements. You are just interest to know whether a particular element already exists or not.
In this tutorial, we have discussed the details of set data structure in Python with the help of various examples. Hope that you will have understood the basic key features of set and practiced all example programs.
Thanks for reading!!!