Home  >  Blog  >   Python  > 

Sets and Unions in Python

Rating: 4
  
 
5688

The Set is an unordered collection of items. Every element is unique (no duplicates) and must be immutable. However, the set itself is mutable (we can add or remove items). The union operation is also a method of set, set.union().

The SETS module provides classes for constructing and manipulating unordered collections of unique elements. Common uses include membership testing, removing duplicates from a sequence, and computing standard math operations on sets such as intersection, union, difference, and symmetric difference. To understand how it works, try the following code:

The result is a set of unique words in the sentence.

Learn how to use Python, from beginner basics to advanced techniques, with online video tutorials taught by industry experts. Enroll for Free Python Training Demo!

MindMajix Youtube Channel

Like sets in mathematics, sets helps in carrying out functions as an intersection and difference which can be of great use.

Symmetric_difference provides those elements that are present in either one of the sets so, set1.symmetric_difference(set2) is same as set2.symmetric_difference(set1)

Now let’s have a look at the result of set1.union(set2)

More elements can be added to a set as follows:

But a set cannot have duplicate entries so you cannot add the same number again and again.

While “add function” allows you to add only one element at a time, you can add more than one element with the help of update function.

Let’s now see the magic of copy() function

https://docs.python.org/2/library/sets.html

Explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

 

 

Join our newsletter
inbox

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
NameDates
Python TrainingMay 21 to Jun 05
Python TrainingMay 23 to Jun 07
Python TrainingMay 28 to Jun 12
Python TrainingMay 30 to Jun 14
Last updated: 11 Apr 2022
About Author
Anjaneyulu Naini

Anjaneyulu Naini is working as a Content contributor for Mindmajix. He has a great understanding of today’s technology and statistical analysis environment, which includes key aspects such as analysis of variance and software,. He is well aware of various technologies such as Python, Artificial Intelligence, Oracle, Business Intelligence, Altrex, etc. Connect with him on LinkedIn and Twitter.

Recommended Courses

1 /15