Operations on Set Objects in Python with Examples
Hi Learner! In this article, we are going to learn to find the common characters of two strings using sets in Python. Let us see how simple it can be to find the common characters of two strings using a simple set operation.
Sets in Python
A set is a collection of elements without any duplicate elements and order. We use curly br a set. Just like list() method, we have a set() method to declare a set object.
Note:-
Since we represent both set and dictionary using {} in Python, we cannot declare an empty dictionary using {}. We make use of the set() method to do the same.
Now, let us learn about a few operations that we can perform on set objects.
1.Union |
Let set1 and set2 be two set objects containing some elements. Using union operator | between the two set objects returns the union of set1 and set2 i.e. a set containing both the unique elements in set1 and set2.
Let us now understand with an example.
set1 = set("Monty") set2 = set("Python3") print(set1) print(set2) print(set1|set2)
Output:
{'o', 'n', 't', 'y', 'M'} {'o', 'n', 't', '3', 'y', 'h', 'P'} {'o', 'n', 't', '3', 'y', 'h', 'M', 'P'}
We can notice that set1|set2 returned a set of elements from both set1 and set2 objects.
2. Difference –
Difference operator – between the two set objects returns the elements present in set1 and not in set2.
Example:
set1 = set('Python3') set2 = set([1,2,3,'t','n']) print(set1) print(set2) print(set1-set2)
Output:
{'P', 't', 'y', 'h', 'n', 'o', '3'} {'t', 1, 2, 3, 'n'} {'P', 'y', 'h', 'o', '3'}
3. Intersection &
Intersection operator + between the two set objects returns the elements present in both set1 and set2.
Example:
set1 = set("Mathematics2") set2 = set(['s','c','i','e','n','c','e',2]) print(set1) print(set2) print(set1&set2)
Output:
{'m', 'a', 'c', 't', 'h', 'e', 's', '2', 'i', 'M'} {2, 'c', 'n', 'e', 's', 'i'} {'s', 'c', 'i', 'e'}
4. Symmetric Difference ^
Symmetric operator ^ between the two set objects returns the elements present in either in set1 or set2 but not both set1 and set2.
Example:
set1 = set("Mathematics2") set2 = set("Science2") print(set1) print(set2) print(set1^set2)
Output:
{'m', 'a', 's', 'e', 'h', 'c', '2', 't', 'i', 'M'} {'n', 'e', 'c', 'S', '2', 'i'} {'m', 's', 'h', 't', 'M', 'a', 'n', 'S'}
Hurrah! we have learned to perform some cool operations on sets.
Thanks for reading this article. I hope you have found this article helpful.
Also, do check our other articles related to sets in Python below:
Leave a Reply