Sets in Python

Pallavi Dhotre

6 months ago

Sets in Python | insideAIML
Table of Content
Introduction
Python Sets
  • Python create set
Python Sets Methods
  • add() and update()
  • discard() and remove()
  • pop()
  • clear()
Python set operations
  • Python Set Union
  • Python Set Intersection
  • Python Set Difference
How to convert python set to list
Ordered set python
Summary

Introduction 

          Using data  structures  in  python  we can  store the  ordered  and unordered data. Lists and tuples are ordered data structures whereas dictionaries and sets are unordered data structures. But do you know how to use python sets to store the data and what operations can be performed on python sets? In this article, we are going to discuss python sets, python set operations, and methods of python sets. 

Python Sets

          Another popular  data  structure  used in  python  is set. Multiple  elements  can be stored under the same name using sets. Sets are used to store the items in an unordered and un-indexed way. Since items in sets are unordered, if we print the set the order of the elements is not fixed. Also, once we create a set we cannot change the elements but we can insert new elements. Elements with the same value are not allowed in sets. Unlike lists, sets do not have an index so we cannot access the elements in an ordered manner. 

Python create set

          To create a python set we use curly brackets {}. Everything in python sets is enclosed within curly brackets { }. Set can have different items with different data types like int, str, boolean, tuple. But the data types like lists and dictionaries which are mutable cannot be inserted as an element of a set. But from lists, we can create a set. 
# Different sets in Python
# set of integers
demo_set = {1, 2, 3}
print(demo_set)
# set of mixed datatypes in python
demo_set = {11.0, "Hello World", (1, 2, 3)}
print(demo_set)
#using a set function in python
demo_set = set([10, 20, 30, 20]) 
print(demo_set)
Output
{1, 2, 3}

{'Hello World', 11.0, (1, 2, 3)}

{10, 20, 30}

Python Sets Methods

          There are several built-in python set methods we will see one by one:

add() and update()

          In python sets, we can add a single element using add() method and multiple elements using the update() method. 
# set of integers
demo_set = {1, 2, 3}
print(demo_set)
demo_set.add(4) #adding single element to the set
print(demo_set)
demo_set.update([5,6,7]) #adding multiple elements to the set
print(demo_set)
output
{1, 2, 3}

{1, 2, 3, 4}

{1, 2, 3, 4, 5, 6, 7}

discard() and remove()

          A specific element of the set can be removed using discard() and remove() methods. If the item is not present in python sets then the discard() method leaves the set as it is. But remove() method throws an error in such a case
See the following code:
# set of integers
demo_set = {1, 2, 3,4,5,6}
print(demo_set)
demo_set.discard(4) #discard element
print(demo_set)
demo_set.remove(7) #try to remove the element which is not present in a set
print(demo_set)
Output
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 5, 6}
Traceback (most recent call last):
  File "C:/Users/Pallavi/PycharmProjects/demo/demo1.py", line 8, in <module>
    demo_set.remove(7) #try to remove the element which is not present in a set
KeyError: 7

pop()

          This method returns the item which is popped from the set.
# set of integers
demo_set = {1, 2, 3,4,5,6}
print(demo_set)
print(demo_set.pop()) #pop() method
output
{1, 2, 3, 4, 5, 6}
1

clear()

          This method is used to remove all the items from the set.
# set of integers
demo_set = {1, 2, 3,4,5,6}
print(demo_set)
demo_set.clear()
print(demo_set) #remove() method
Output
{1, 2, 3, 4, 5, 6}
set()

Python Set Operations

          Unlike mathematics, python sets also perform the same operations. The operations that can be performed on sets are union, intersection, and difference.
  Python set operations | insideAIML - Image Reference: <a href="https://miro.medium.com/max/1076/1*Q9SsNMCFFZ7Y4ThXiQyHjQ.png">Medium</a>

Python Set Union

          To perform the union operation on two sets we use ‘|’ this operator. Also, we can use the union() method.  It returns all the items from both sets. See the following code:
demo_set1 = {1, 2, 3,4,5,6} #set1
demo_set2 = {11, 12, 13,14,15,16} #set2
print(demo_set1|demo_set2) #python set union using | operator
print(demo_set2.union(demo_set1)) #using union() method
Output
{1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 15, 16}

{1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 15, 16}

Python Set Intersection

          The intersection of two sets returns the common items in both sets.  For intersection, we can use the ‘&’ operator. Also, this can be achieved using the intersection() method. See the following code:
demo_set1 = {1, 2, 3,4,5,6} #set1
demo_set2 = {1, 2, 13,14,15,16} #set2
print(demo_set1 & demo_set2) #python set intersection using & operator
print(demo_set2.intersection(demo_set1)) #using intersection() method
Output
{1, 2}

{1, 2}

Python Set Difference

          The difference between the two sets returns the elements which are present in the first set but not in the second set. ‘-’ operator is used for calculating the difference. Also, this is achieved through the difference() method. See the following code:
demo_set1 = {1, 2, 3,4,5,6} #set1
demo_set2 = {1, 2, 13,14,15,16} #set2
print(demo_set1 - demo_set2) #python set difference using - operator
print(demo_set1.difference(demo_set2)) #using  function difference()
Output
{3, 4, 5, 6}
{3, 4, 5, 6}

How to convert python set to list?

          To convert the python set to list we use built-in list() function. See the following example
demo_set1 = {1, 2, 3,4,5,6} #set1
print(demo_set1)
set_to_list=list(demo_set1) #converting python set to list
print(set_to_list)
Output:
{1, 2, 3, 4, 5, 6}

[1, 2, 3, 4, 5, 6]

Ordered Set Python

          Generally set is an unordered and un-indexed collection of elements. But the ordered set follows the properties of lists and sets.  The ordered set remembers the order in which items are inserted. For this first you need to install the ordered set in python using the following command:
pip install ordered-set
Example:
from ordered_set import OrderedSet
number = OrderedSet('198750') #using ordered set python
print(number) 
Output
OrderedSet(['1', '9', '8', '7', '5', '0'])

Summary

          In this article, we discussed python sets, python set methods, python set operations, convert python set to list, and ordered set python. Sets are used to store the data in an unordered and un-indexed manner. Since items in sets are unordered, if we print the set the order of the elements is not fixed. Also, once we create a set we cannot change the elements but we can insert new elements. Elements with the same value are not allowed in sets. Unlike lists, sets do not have an index so we cannot access the elements in an ordered manner.  We hope you enjoyed the article. If you have any related queries, feel free to ask in the comment section below. 
    
Liked what you read? Then don’t break the spree. Visit our blog page to read more awesome articles. 
Or if you are into videos, then we have an amazing Youtube channel as well. Visit our InsideAIML Youtube Chanel to learn all about Artificial Intelligence, Deep Learning, Data Science and Machine Learning. 
Keep Learning. Keep Growing. 
    

Submit Review