Sets in Python with best 10+ example

Sets in Python are an unordered collection of unique elements. We can construct them by using the set() function.
Every set element is unique (no duplicates) and must be immutable (cannot be changed). However, a set itself is mutable. We can add or remove items from it.

Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc.

Let’s go ahead and make a set to see how it works.

Please read the previous topic for more understanding about Python
Control Statements in Python

List in Python
Tuple in Python

Creating Sets in Python

A set is created by placing all the items (elements) inside curly braces {}, separated by a comma, or by using the built-in set() function.

It can have any number of items and they may be of different types (integer, float, tuple, string, etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements.

Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements, we use the set() function without any argument.

# Empty Sets in Python
# Intialize a set with set() method
mySet = set()
print(mySet)
print(type(mySet))


# Assigned empty acurly braces {} -- It will consider as Dictionary
myData = {}
print(myData)
print(type(myData))

mySet = {1, "Hello", "World"}
print(mySet)
print(type(mySet))

O/P –

set()
<class 'set'>
{}
<class 'dict'>
{1, 'World', 'Hello'}
<class 'set'>
# set of integers
mySet = {1, 2, 3}
print(mySet)

# set of mixed datatypes
mySet = {3.4, "Infosyntax", (10, 20, 30)}
print(mySet)

O/P –

set()
{}
<class 'dict'>
{1, 2, 3}
<class 'set'>
{(10, 20, 30), 3.4, 'Infosyntax'}

Checking the type of set.

print(type(mySet))

O/P –

<class 'set'>

Note:
Every set element is unique (no duplicates).

mySet = {10, 30, 10, 20, 50, 60, 25, 20}
print(mySet)

O/P –

{10, 50, 20, 25, 60, 30}

Note:
We can also create a set from the list in python.


#Create Sets from List
mySet = set([10, 20, 10, 30])
print(mySet)

O/P –

{10, 20, 30}

Note:
Set cannot have mutable items. If you add a mutable item in the set’s element then it will raise the error.

my_set = {89, 76, [10, 20]}

O/P –

Sets in Python

Modifying a Sets in Python

We can add a single item using add() method and add multiple items using the update method. The update() method can take tuples, lists, strings or other sets as its argument.
Sets in python are unordered, indexing has no meaning. We cannot access or change an element of a set using indexing or slicing. Set data type does not support it.

mySet = {10, 20, 30}

#Try access item using index
print(mySet(mySet[1]))

O/P –

Adding a new element in Set

We can add a new element or multiple elements in set. Let’s see the below example.

# Add single element in Set
mySet = {10, 20, 30}

# Before Add
print(mySet)

mySet.add(40)
mySet.add(20)

# After add
print(mySet)

O/P –

{10, 20, 30}
{40, 10, 20, 30}
# Add multiple element in Set
mySet = {10, 20, 30}

# Before Add
print(mySet)

mySet.update([20, 40, 50])

# After add
print(mySet)

# Multiple object
mySet.update([100, 80, 90], {60, 70 })

# After add
print(mySet)

O/P –

{10, 20, 30}
{40, 10, 50, 20, 30}
{100, 70, 40, 10, 80, 50, 20, 90, 60, 30}

Remove element from Set

Remove()

This function removes its element from the set.
KeyError occurs if the value is not in the set.

mySet = {10, 30, 10, 20, 50, 60, 25, 20}

print(mySet)

mySet.remove(30)

print(mySet)

O/P –

{10, 50, 20, 25, 60, 30}
{10, 50, 20, 25, 60}
mySet.remove(35)

O/P –

Discard()

It is also used to remove the element from sets in python but it does not cause an exception if the value is not in the set.

mySet = {10, 30, 10, 20, 50, 60, 25, 20}

print(mySet)

mySet.discard(30)

#35 is not in the set and it's not raised the error.
mySet.discard(35)

print(mySet)

O/P –

{10, 50, 20, 25, 60, 30}
{10, 50, 20, 25, 60}

Pop()

You can also remove an arbitrary set element and return it with the pop method, but Sets are unordered so you do not know which element will be returned.
KeyError occurs if the set is empty when you call the pop method.

mySet = {10, 30, 10, 20, 50, 60, 25, 20}

print(mySet)

print(mySet.pop())

print(mySet)

O/P –

{10, 50, 20, 25, 60, 30}
10
{50, 20, 25, 60, 30}

Clear()

It will remove all the items on the set.

mySet = {10, 30, 10, 20, 50, 60, 25, 20}

print(mySet)

mySet.clear()

print(mySet)

O/P –

{10, 50, 20, 25, 60, 30}
set()

Set Membership

We can check if a value is in a set or not by using the keyword in. Notice that the membership test is only for the value is present and not.

mySet = {10, 30, 10, 20, 50, 60, 25, 20}

print( 20 in mySet)
print( 32 in mySet)

O/P –

True
False

Iterating Through a Sets in Python

Set are iterable, so you can process each set element with a for a loop.

mySet = {10, 30, 10, 20, 50, 60, 25, 20}

for value in mySet:
    print(value)

O/P –

10
50
20
25
60
30

Comparing Sets in Python

OperatorDescription
==Return true if two set’s elements are equal, else false.
!=Return true if two set’s elements are not equal, else false.
<The left set is a proper subset of a right-side set. 
<=Whether the set to its left is improper.
issubset() The left set is a subset of the one to its right set
> Whether the set its left is a proper superset of the one to its right. 
>=Whether the set to its right is improper.
issuperset() The left set is a superset of the one to its right set
Comparing Sets in Python
set1 = {1,2,3} 
set2 = {2, 3, 4}

print(set1 == set2)
print(set1 != set2)

O/P –

False
True
set1 = {1,2,3} 
set2 = {1, 2, 3, 4}

print(set1 < set2)
print(set1 <= set2)

print(set1.issubset(set2))

O/P –

True
True
True
set1 = {1, 2, 4, 5, 6} 
set2 = {1, 2, 3, 4}

print(set1 > set2)
print(set1 >= set2)

print(set1.issuperset(set2))

O/P –

False
False
False

Mathematical Operation in Set

Union

The union of two sets consists of all the elements from both sets in python.

set1 = {1, 2, 3} 
set2 = {2, 3, 4}

# | using for union
print(set1 | set2)

# union method 
print(set1.union(set2))

O/P –

{1, 2, 3, 4}
{1, 2, 3, 4}

Intersection

The intersection of two sets is a set consisting of all the unique elements that the two sets have in common.

set1 = {1, 2, 3} 
set2 = {2, 3, 4}

# | using for Intersection
print(set1 & set2)

# Intersection method 
print(set1.intersection(set2))

O/P –

{2, 3}
{2, 3}

Difference

The difference between two sets is a set consisting of the element in the left operand that is not in the right operand.

set1 = {1, 2, 3} 
set2 = {2, 3, 4}

# | using for difference
print(set1 - set2)

# Intersection method 
print(set1.difference(set2))

O/P –

{1}
{1}

Symmetric Difference

The symmetric difference between two sets is a set consisting of both sets that are not in common with one another.

set1 = {1, 2, 3} 
set2 = {2, 3, 4}

# ^ using for symmetric difference
print(set1 ^ set2)

# symmetric_difference method 
print(set1.symmetric_difference(set2))

O/P –

{1, 4}
{1, 4}

Disjoint

The isdisjoint() method will automatically convert iterables to set and check whether the sets are disjoint or not.

  • returns True – if the two sets are disjoint.
  • returns False – if the twos sets are not disjoint.
set1 = {10, 20, 30} 
set2 = {40, 50, 60}
set3 = {30, 40}


print("set1 and set2 are disjoint?", set1.isdisjoint(set2))
  
print("set1 and set3 are disjoint?", set1.isdisjoint(set3))

O/P –

set1 and set2 are disjoint? True
set1 and set3 are disjoint? False

Frozenset in Python

FrozenSet is a new class that has the characteristics of a set, but its elements cannot be changed once assigned. While tuples are immutable lists, frozen sets are immutable sets.
Sets being mutable are unhashable, so they can’t be used as dictionary keys. On the other hand, frozen sets are hashable and can be used as keys to a dictionary.

Frozen sets can be created using the frozenset() function.

# Frozensets
myFrozenset = frozenset([10, 20, 30, 40])
print(myFrozenset)

O/P –

frozenset({40, 10, 20, 30})
myFrozenset.add(50)

O/P –

Sets in Python

Please download the example of Sets in Python

Leave a Comment

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