Python Set Types


The sets are basically an unordered collection of distinct hash-table objects. We can use the set for some mathematical operations like set union, intersection, difference etc. We can also use set to remove duplicates from a collection.

The set do not record the element position. It does not support the indexing, slicing or other sequence related operations.

In python there are basically two types of sets. The set and the frozenset. The set type is mutable, whether the frozenset is immutable. We can perform add(), remove() and these kind of operations on set, but it is not possible for frozenset.

Some of the set related methods and operations are as follows −

Method len(s)

The len() method returns the number of elements in the set.

Operation (x in s) or (y not in s)

The in and not in operations are used to check the membership of an element in the set. In the first statement (x in s), it will return true, when the value x is available in set s. The second one (y not in s) will return true, when the element y is not present in the set.

Method isdisjoint(other_set)

This method will check whether the other_set is disjoint with the current set or not. If at least one element is common for both of them, the method will return false.

Method issuperset(other_set)

This function returns true, when all of the elements in other_set set is also present in the current set. It basically checks whether the current set is superset of the other_set or not.

Method union(other_set)

The union() function returns a new set by collecting all of the elements from current set and the other_set.

Method intersection(other_set)

The intersection() function returns a new set by collecting common elements from the current set and the other_set.

Method difference(other_set)

The difference() method will return a set, where the final set contains all of the elements of the first set except the common elements of those two sets.

Method add(elem)

Add the element elem in the set.

Method discard(elem)

Remove the element elem from the set. This will work when the elem is present in the set. There is another method called remove(). In the remove(), it will raise KeyError if the item is not present in the set.

Example Code

Live Demo

mySet1 = {1, 2, 5, 6}
mySet2 = {8, 5, 3, 4}
mySet3 = set(range(15)) # all elements from 0 to 14 in the set
mySet4 = {10, 20, 30, 40}
print(set(mySet1.union(mySet2)))
print(set(mySet1.intersection(mySet2)))
print(set(mySet1.difference(mySet2)))

print(mySet3.issuperset(mySet1))
print(mySet1.isdisjoint(mySet4))

mySet4.add(45)
print(mySet4)

mySet4.discard(40)
print(mySet4)

Output

set([1, 2, 3, 4, 5, 6, 8])
set([5])
set([1, 2, 6])
True
True
set([40, 10, 20, 45, 30])
set([10, 20, 45, 30])

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements