## Set in Python

A set in Python is mutable, iterable, and does not have any duplicate elements. It is an unordered collection of elements which means that a set is a collection that stores elements of different Python Data Types. Remember that a set in Python doesn’t index the elements in a particular order. Let us look at some of the properties of sets in Python. Sets in Python are usually used to perform some mathematical functions such as union, intersection, etc.

- In Python sets, elements don’t have a specific order.
- Sets in Python can’t have duplicates. Each item is unique.
- The elements of a set in Python are immutable. They can’t accept changes once added.
- But, don’t get confused with the fact that sets in Pyhton are mutable. Python sets allow addition and deletion operations.

**Watch this video on Python:**

*Become a master of Python by going through this online Python Course in Toronto!*

One of the major advantages of using sets in Python is that unlike some other data types like Python Lists, sets contain a highly optimized method for the sole purpose of checking whether a particular element is included in a set or not.

Also, since sets in Python are mutable, we can add and remove elements from a set; however, every element that is added in the set must be unique and immutable, that is, we cannot change elements once they have been added.

In this module, we will learn all about sets in order to get started with them. Following is the list of all topics that we will be covering.

So, without any further delay, let’s get started.

## Instantiate a Set in Python

- Using commas to separate and curly braces to group elements

myset = {“apple”, “banana”, “cherry”} print(myset) Output: {‘cherry’, ‘banana’, ‘apple’}

- Using the in-built set() method with the elements that we want to add as the parameters

myset = set((“apple”, “banana”, “cherry”)) # note the double round-brackets print(myset) Output: {‘cherry’, ‘banana’, ‘apple’}

Remember that once a set is created we can’t change that set. We can only add elements. We can remove and then add elements but cannot change the existing elements. Now, let us see how to add items in a Python set.

**Python Set operations**

**Adding Elements to a Set in Python**

- Using the add() method with the element as the parameter:

myset = {“apple”, “banana”, “cherry”} myset.add(“orange”) print(myset) Output: {‘cherry’, ‘orange’, ‘banana’, ‘apple’}

- Using update()

myset = {“apple”, “banana”, “cherry”} myset.update([“orange”, “mango”, “grapes”]) print(myset) Output: {‘cherry’, ‘mango’, ‘banana’, ‘apple’, ‘orange’, ‘grapes’}

*Get certified from this top Python Course in Singapore today!*

**Removing elements from sets in Python**

Remove operation can be performed by using the following methods.

- Using the remove() method:

myset = {“apple”, “banana”, “cherry”} myset.remove(“banana”) print(myset) output: {‘cherry’, ‘apple’}

Note: If the item to be removed does not exist, remove() will raise an error.

2. Using discard():

myset = {“apple”, “banana”, “cherry”} myset.discard(“banana”) print(myset) Output: {‘cherry’, ‘apple’}

Note: If the item to be removed does not exist, discard() will not raise an error.

3. Using pop():

Remember that pop() will remove the last item of a set. Since sets are unordered, we should avoid performing pop() in sets.

myset = {“apple”, “banana”, “cherry”} x = myset.pop() print(x) print(myset) Output: {‘banana’, ‘apple’}

**Printing the Length of a Set in Python**

To print the length of a set, we can simply use the in-built len() method as shown below:

myset = {“apple”, “banana”, “cherry”} print(len(myset)) Output: 3

**Emptying a Python Set Completely**

To clear a set completely, we can use either the clear() method or the del() method.

- Using clear():

myset = {“apple”, “banana”, “cherry”} myset.clear() print(myset)

- Using del():

myset = {“apple”, “banana”, “cherry”} del myset print(myset) Output: Traceback (most recent call last): File “”, line 1, in NameError: name ‘myset’ is not defined

As discussed above, sets in Python are used to carry out mathematical set operations such as union, intersection, etc. Let’s see a few examples of these mathematical operations.

*Learn end-to-end Python concepts through the Python Course in Hyderabad to take your career to a whole new level!*

**Sets Union**

To perform union, we use “|” operator. We can also use an in-built method called union(), which will give the same result.

The result of the union of two sets, say Set A and Set B, is a set containing the elements of both sets.

The following code block shows the union of Set A and Set B:

Set_A = {1,2,3,4,5} Set_B = {4,5,6,7} print(Set_A | Set_B) Output: {1, 2, 3, 4, 5, 6}

**Set Intersection**

To perform intersection, we use ‘&’ operator. We can also use the in-built Python Function named as intersection() to get the same result.

The intersection of two sets, say Set A and Set B, can result in a set that contains the elements that are common in both sets, that is, the overlapping part in the diagram below.

The following code block shows the union of Set A and Set B:

Set_A = {1,2,3,4,5} Set_B = {4,5,6,7} print (Set_A & Set_B) Output: {4, 5}

*Are you interested in learning Python from experts? Enroll in our Python Course in Bangalore now!*

**Common Python Set methods**

Method | Description |

update() | It updates a set with the union of this set and others. |

add() | It adds an element to a set. |

clear() | It removes all elements from a set. |

copy() | It returns a copy of a set. |

difference() | It returns a set containing the difference between two or more sets. |

difference_update() | It removes the items in a set that are also included in another, specified set. |

discard() | It removes a specified item. |

remove() | It removes a specified element. |

pop() | It removes an element from a set. |

intersection() | It returns a set, that is the intersection of two other sets. |

intersection_update() | It removes items in a set that are not present in another, specified set(s). |

isdisjoint() | It returns whether two sets have an intersection or not. |

issubset() | It returns whether another set contains a specific set or not. |

issuperset() | It returns whether a set contains another set or not. |

symmetric_difference() | It returns a set with the symmetric differences of two sets. |

union() or | | It returns a set containing the union of sets. |

intersection or & | It returns a set comprising common elements in two sets. |

With this, we come to the end of this module in Python Tutorial. Now, if you are interested in knowing why Python is the most preferred language for data science, you can go through this blog in Python for Data Science

Further, check out our Python course for certification and prepare to excel in career with our free Python interview questions listed by the experts.