Python Set

Table of Contents

What is a Python Set ?

A set is an unordered collection with no duplicate elements.
A set is mutable data type
The elements of set should be hashable type.
Set objects support mathematical operations like union, intersection, difference, and symmetric difference.

How to create a Python Set ?

To create a set object we need to use curly braces {} or the set() function.
Comma separated values within curly braces creates a set.
To create using set() we need to pass an iterable (like list, tuple or dictionary)
Example:

myset = {"pythoneasy", 2016, "english"}
print(myset) # prints {2016, 'pythoneasy', 'english'}
myset2 = set(["pythoneasy", 2016, "english"]) # A list passed to set()
print(myset2) # prints {2016, 'pythoneasy', 'english'}
print(type(myset2)) # <class 'set'>
{2016, 'english', 'pythoneasy'}
{2016, 'english', 'pythoneasy'}
<class'set'>

More Examples
Set only can have hasable type elements (immutable type and userdefined class objects)

myset = {"pythoneasy", 2016, [2, 3, 4]} # [2, 3, 4] is not a hashable type
print(myset)
TTraceback (most recent call last): File "D:/pythoneasy/set_example.py", line 1, in <module> myset = {"pythoneasy", 2016, [2, 3, 4]} TypeError: unhashable type: 'list'

in the above example [2, 3, 4] is list not a hashable type, so it raises error

Create an empty Set in Python

To create an empty set we have to use set() function, not {}
Because {} creates an empty dictionary not set

s1 = {}
s2 = set()
print(type(s1)) # prints <class 'dict'>
print(type(s2)) # prints <class 'set'>
<class 'dict'>
<class 'set'>

How to change a Python Set ?

Add a new value to set

Using add() function we can add a single element to a set

myset = {1, 2, 3}
myset.add(4)
myset.add(5)
print(myset)

{1, 2, 4, 5, 3}
Sets are unordered so the elements might be printed in any order
Using update() we can add a iterable like list , tuple to existing set elements

myset = {1, 2, 3}
myset.update([4, 5])
myset.update((6, 7))
print(myset)

{1, 2, 3, 4, 5, 6, 7}
4 ,5 , 6 and 7 became each element of the set

Remove an item from set

We can remove items from a set using methods remove() and discard()

myset = {1, 2, 3, 4, 5, 6}
myset.remove(2)     # removes 2 from set
myset.discard(4)    # removes 4 from set
print(myset)

{1, 3, 5, 6}
remove() raises an error if the item is not available in set, but discard() does not
If item is not available the set remain unchanged if we are using discard()

myset = {1, 2, 3, 4, 5, 6}
myset.discard(9)    # 9 is not available
print(myset)        # prints {1, 2, 3, 4, 5, 6}
myset.remove(9)     # raises error
print(myset)
{1, 2, 3, 4, 5, 6} Traceback (most recent call last): File "D:/pythoneasy/set_example.py", line 4, in <module> myset.remove(9) KeyError: 9
Click any Link
to navigate to certain page easily
Write a line to us
Your Email
Title
Description