Sets in Python and Built-in-method
In today’s article, we will explore sets in Python. You must have learned in your Math class about sets and if you remember a set is a collection of elements but today we will dig into the details of sets in Python which is close to, but not the same as, mathematical sets. Set is one of the four built-in data types in Python along with List, Tuple, and Dictionary, all with different qualities and usage. It is used to store collections of data and is written with curly brackets.
In Python, sets store unordered values and cannot have multiple occurrences of the same element. It makes sets highly useful to efficiently remove duplicate values from a list or tuple and to perform common math operations like unions and intersections.
Let’s get started. :-)
What is Set in Python?
A set is a data type consisting of a collection of unordered elements. These elements can be on any data type as sets, unlike arrays, are not type-specific. Sets are mutable(changeable) and do not have repeated copies of elements.
When to use sets in Python?
Sets in Python are used when-
- The order of data does not matter
- You do not need any repetitions in the data elements
- You need to perform mathematical operations such as union, intersection, etc
How to create a set in Python?
Sets in Python can be created in two ways-
- enclosing elements within curly braces
- by using the set() function
Now let us move ahead to Built-in-method of Sets.
1.add()
adds a given element to a set if the element is not present in the set in Python.
2.difference()
The method returns a set that contains the difference between two sets.
3.difference_update
The method updates the set by removing items found in specified sets.
4. discard()
The method removes the specified item from the set.
5.intersection()
The method returns a set that contains the similarity between two or more sets.
6.intersection_update
The method removes the items that are not present in both sets.
7.disjoint()
Two sets are said to be disjoint when their intersection is null.
8. issubset()
The method returns True if all items in the set exist in the specified set, otherwise, it returns False.
9.isuperset()
The method returns True if all items in the specified set exist in the original set, otherwise, it returns False.
10.symmetric_difference()
The method returns a set that contains all items from both sets, but not the items that are present in both sets.
11.symmetric_difference_update()
The method updates the original set by removing items that are present in both sets and inserting the other items.
12.union()
The method returns a set that contains all items from the original set, and all items from the specified set(s)
#vevcodelab