Sets in Python

Sets in Python

Sets in Python

Set is an unordered collection of unique elements. Items in sets are immutable which can not be replaced or changed. Elements of a set can not be accessed using indexing or a set can not be sliced.

Creation of a Set in Python

There are two methods to create a set in Python. The first one is set() function and the second is to use curly braces {}.

1- Creating a Set in Python Using Curly Brace {}

To create a set using {} is very simple for example
>>>set1={1,2,3,3,4,5}
>>>print(set1)
Output: {1, 2, 3, 4, 5} # Duplicate elements are not allowed

1- Creating a Set in Python using set() Function

>>> set1=set([1,2,3,3,4,5])
>>>print(set1)
{1, 2, 3, 4, 5} # Duplicate elements are not allowed

Print Set Elements

As set’s elements can not be indexed or sliced you have to print whole set.
>>> for s in set1:
… print(s)

Add Elements to a Set

add() function is used to an element in a set for example.
If you want to add an element 6, then it will be done in the following way.
>>>set1.add(6)
>>>print(set1)
Output: {1, 2, 3, 4, 5, 6}

Remove Elements of a Set

There are two in-built methods to remove an element from a set.
1-remove()
2-discard()
The only difference between is that, if an element is not present in set then remove() function will through an error. However, discard() will not
through an error and silently print the original set.
For example,
>>>set1.remove(4)
>>>print(set1)
Output:{1, 2, 3, 5, 6}

If you remove 7 from the set set1, the interpreter will through the following error.
>>>set1.remove(7)
Original exception was:
Traceback (most recent call last):
File “”, line 1, in
KeyError: 7
If you use discard function, it will not through any error.
>>>set1.discard(7)
>>>print(set1)
Output:{1, 2, 3, 5, 6}

Set Operations in Python

Set operations union, intersection, difference and symmetric difference can be performed of sets as in mathematics.

Here, define another set set2.

>>>set2={5,6,7,8,9,10}

Union Operation

Then | symbol is used to perform union operation between two sets, then union of sets set1 and set2 is set3.
>>> set3=set1|set2
>>> print(set3)
Output: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Intersection Operation

Symbol & is used to perform intersection operation between two sets, then intersection of sets set1 and set2 is set3.
>>> set3=set1&set2
>>> print(set3)
Output: {5, 6}

Set-Difference Operation

>>> set3=set1-set2
>>>print(set3)
{1, 2, 3, 4}

Symmetric Difference of Two Sets

Symmetric difference of two sets is defined as below in terms of union, difference and intersection.
That is
set3= set1|set2-set1 & set2

However, Python provides symbol ^ for direct symmetric difference of two sets.
>>> set3=set1^set2
>>> print(set3)
{1, 2, 3, 4, 7, 8, 9, 10}

Leave a Comment

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

©Postnetwork-All rights reserved.