Python set operations

Python Sets are an unordered collection of unique elements.It does not allow duplicates.You can simply create a set using set() function

Output:

{1}

Please Note the curly brackets. This does not indicate a dictionary!

We know that a set can have only unique element, So what happens when we try to add something that is already in a set?

Output:

{1, 2}

Output:

{1, 2}

So if element is already present, set won’t add it again as set does not allow duplicates
Let’s say you have list and it has duplicate elements and you don’t want duplicate elements, you can simply cast a list with multiple repeated elements to a set to get the unique elements.
For example:

# Create a list with repeats l = [1,2,1,4,2,3,4,5,6,6] # Cast as set to get unique values s=set(l) print(s)

Output:

{1, 2, 3, 4, 5, 6}

That’s all about basic understanding of set.
Now let’s go through various methods of set.


add

add elements to a set. Please note that set won’t add duplicate elements

{1, 2}

clear

removes all elements from the set

set()

copy

returns a copy of the set.As it is copy of set, changes to it won’t impact original set.

{1, 2, 3}

{1, 2, 3, 4}

{1, 2, 3}

difference

difference returns the difference of two or more sets. The syntax is:

set1.difference(set2)
For example:

{4}

difference_update

the method returns set1 after removing elements found in set2
difference_update syntax is:

set1.difference_update(set2)

{2, 3}

discard

Removes an element from a set if it is present else do nothing.

{1, 3}

intersection

Returns the intersection of two or more sets as a new set.It means it returns common element present in two sets.

{1, 2}

intersection_update

intersection_update will update a set with the intersection of itself and another.

{1, 2}

isdisjoint

This method will return True if two sets have a null intersection.

Output:

False
True
True

issubset

This method reports whether another set contains this set.

Output:

True

issuperset

This method will check whether this set contains another set.

Output:

True

union

Returns the union of two sets. It means it returns all the elements present in either of sets.

{1, 2, 3, 4}

update

Update a set with the union of itself and others.

Output:

{1, 2, 3, 4}

That’s all about set operations in python.

Leave a Reply

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