Mindmajix

Sets and Unions

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:

Screenshot_41

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

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

Screenshot_42

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)

Screenshot_43

More elements can be added to a set as follows:

Screenshot_44

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

Screenshot_45

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.

Screenshot_46

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

Screenshot_47

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

          Enroll for Instructor Led Live Python Training


0 Responses on Sets and Unions"

Leave a Message

Your email address will not be published. Required fields are marked *

Copy Rights Reserved © Mindmajix.com All rights reserved. Disclaimer.
Course Adviser

Fill your details, course adviser will reach you.