Sets in Python

Amit Dhanwani on March 1, 2023

Sets in Python

Introduction

Python has four types of structures for working with data collections: list, set, tuple, and dictionary. We’ll look at the sets in Python, in this blog.

A set is a form of data collection that allows for the storage of several things in a single variable in Python. Since sets in Python are unordered, the order in which they are returned is not necessarily constant.

Additionally, the objects in the set cannot be modified since they are immutable. Items can be added and removed, though.

The primary benefit of using a set over a list is that it includes an extremely efficient technique for determining if a particular member is present in the set.

Creating a set in Python

The built-in set() method may be used to generate sets with an iterable object or a series by enclosing the sequence in curly braces and separating them with a comma. Then, assign it to a Python variable.

Example:

# Creating a Blank Set
setC = set()
print("Blank Set: ")
print(setC)
# Creating a Set with the use of a String
setC = set("codingal")
print("\nSet with the use of String: ")
print(setC)
# Creating a Set with the use of Constructor (Using object to Store String)
string = 'codingal'
setC = set(string)
print("\nSet with the use of an Object: " )
print(setC)
# Creating a Set with the use of a List
setC = set(["codingal", "kids", "love"])
print("\nSet with the use of List: ")
print(setC)

Blank Set:

set()

Set with the use of String:

{'n', 'o', 'i', 'a', 'd', 'g', 'c', 'l'}

Set with the use of an Object:

{'n', 'o', 'i', 'a', 'd', 'g', 'c', 'l'}

Set with the use of List:

{'kids', 'codingal', 'love'}

An empty dictionary, not an empty set, is what you get if you define an empty set as the following code. Utilizing the type() method, we validate this.

Example:

setC = {}
print(type(setC))

<class 'dict'>

A set only includes unique items, however, when a set is created, it is also possible to pass numerous duplicate values. The arrangement of elements in a set is random and fixed.

A set’s items don’t have to be of the same type; different values of mixed data types can be supplied to the set.

Example:

# Creating a Set with a List of Numbers (Having duplicate values)
setC = set([2020, 2021, 2020, 2022, 2023, 2023, 2021])
print("\nSet with the use of Numbers: ")
print(setC)
# Creating a Set with a mixed type of values (Having numbers and strings)
setC = set([2020, 2023, 'codingal', 2021, 'kids', 2022, 'love'])
print("\nSet with the use of Mixed Values")
print(setC)

Set with the use of Numbers:

{2020, 2021, 2022, 2023}

Set with the use of Mixed Values

{'kids', 2020, 2021, 2022, 2023, 'love', 'codingal'}

A set in python can be changeable, but it cannot include mutable elements like a list, set, or dictionary.

Example:

codingal={[1,2,3],4}
print(codingal)

Traceback (most recent call last):

File "main.py", line 1, in <module>

codingal={[1,2,3],4}

TypeError: unhashable type: 'list'

Accessing a set in Python

The only way to access a set in Python is all at once because indexing is not supported. Sets cannot be sliced since they do not support indexing.

It is possible to access the individual elements by looping through the set. The for loop, which enables us to iterate over the set once for each item in it, is the most popular method.

Example:

codingal={'kids', 2020, 2021, 2022, 2023, 'love', 'codingal'}
for i in codingal:
print(i)

kids

2020

2021

2022

2023

love

codingal

For each iteration of the loop, this call to the print function would print each item individually, stopping after the final item in the set.

The in keyword is the alternative technique. It produces a boolean result indicating if a certain item is present in the set. Because Python is in the set, for instance, the following code block would print true to the console.

Example:

codingal={'kids', 2020, 2021, 2022, 2023, 'love', 'codingal'}
print("kids" in  codingal)

True

Adding elements to a set in Python

Using add() method

The built-inadd() method can be used to add elements to the set. When utilizing the add() function, only one element may be added to the set at a time; loops are used to add multiple elements at once.

Tuples can be added to a set as elements even if lists cannot since tuples are immutable and hence hashable, but lists cannot because they are not hashable.

We can add the elements using the for loop in the set.

Example:

# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)
# Adding element to the Set
set1.add(2020)
set1.add("codingal")
print("\nSet after Addition of elements: ")
print(set1)
# Adding tuple to the Set
set1.add(("kids", 2023))
print("\nSet after Addition of elements: ")
print(set1)
# Adding elements to the Set using Iterator
for i in range(2020, 2024):
set1.add(i)
print("\nSet after Addition of elements from 2020-2023: ")
print(set1)

 Initial blank Set:

set()

Set after Addition of elements:

{2020, 'codingal'}

Set after Addition of elements:

{2020, 'codingal', ('kids', 2023)}

Set after Addition of elements from 2020-2023:

{2020, 2021, 2022, 2023, 'codingal', ('kids', 2023)}

 

Using update() method

Theupdate() function is used for the addition of two or more components. In addition to other sets, the update() function also accepts lists, strings, tuples, and other inputs. All of these situations prevent using duplicate items.

Example:

# Addition of elements to the Set using update() function
set1 = set([2020, 2021, (2022, 2023)])
set1.update([2024, 2025])
print("\nSet after Addition of elements using Update: ")
print(set1)

Set after Addition of elements using Update:

{2020, 2021, 2024, 2025, (2022, 2023)}

Deleting elements from the set in Python

There are more ways to remove items from a set than to add new ones. The primary explanation is that sets return values in random orders because they are unordered. Due to this contradiction, removing objects without directly aiming at them might be challenging.

Using remove() method or discard() method

The built-in remove() method may be used to delete elements from the Set, however, if the element isn’t present in the set, a KeyError is raised.

To delete entries from a set without raising a KeyError, use discard(); if the element does not exist in the set, it remains unaffected.

Example:

# Creating a Set
set1 = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
print("Initial Set: ")
print(set1)
# Removing elements from Set using remove() method
set1.remove(9)
set1.remove(2)
print("\nSet after Removal of two elements: ")
print(set1)
# Removing elements from Set using discard() method
set1.discard(7)
set1.discard(5)
print("\nSet after Discarding two elements: ")
print(set1)
# Removing elements from Set using iterator method
for i in range(1, 5):
set1.remove(i)
print("\nSet after Removing a range of elements: ")
print(set1)

Initial Set:

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

Set after Removal of two elements:

{1, 3, 4, 5, 6, 7, 8, 10, 11, 12}

Set after Discarding two elements:

{1, 3, 4, 6, 8, 10, 11, 12}

Traceback (most recent call last):

File "main.py", line 20, in <module>

set1.remove(i)

KeyError: 2

Because element 2 is missing from the set, as you can see, we encountered a KeyError while attempting to remove it from the set using a for loop. Let us correct that:

Example:

# Removing elements from Set using the iterator method
for i in range(1, 5):
set1.discard(i)
print("\nSet after Removing a range of elements: ")
print(set1)

Set after Removing a range of elements:

{6, 8, 10, 11, 12}

 

Using pop() method

The Pop() method may also be used to remove one element from a set and return it, however it only removes the set’s last element. You may use the pop() function on a set just like you would on a dictionary. There is no need for a debate, though.

There is no way to supply an index to the pop method because a set doesn’t support indexing. So it produces an arbitrary object.

Additionally, it writes out the object that was clicked.

Example:

# Creating a Set
set1 = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
print("Initial Set: ")
print(set1)
# Removing element from the Set using the pop() method
set1.pop()
print("\nSet after popping an element: ")
print(set1)

Initial Set:

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

Set after popping an element:

{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

 

Using clear() method

The clear() method for a dictionary may also be used with a Python set, just as the pop method().

In order to eliminate every item from a set, we may utilise the clear approach, which keeps the set’s overall structure while eliminating all individual items from it.

Example:

#Creating a set
set1 = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
print("\n Initial set: ")
print(set1)
# Removing all the elements from set using clear() method
set1.clear()
print("\nSet after clearing all the elements: ")
print(set1)

Initial set:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

Set after clearing all the elements:
set()

 

Python sets functions

 

When you apply a function to a Python set, it executes operations on the set and returns a value.

  1. len()

The length of a set is returned by the len() method. This is the number of elements in it.

Example:

codingal=('kids', 2020, 2021, 2022, 2023, 'love', 'codingal')
print("The number of elements present in codingal set is:", len(codingal))

The number of elements present in codingal set is: 7

 

  1. max()

The item from the set with the highest value is returned by this method.

Example:

codingal=(2020, 2021, 2022, 2023)
print("The maximum element present in codingal set is:", max(codingal))

The maximum element present in codingal set is: 2023

 

  1. min()

The Python set’s lowest-valued item is returned by the min() method, similarly like by the max() function.

Example:

codingal=(2020, 2021, 2022, 2023)
print("The maximum element present in codingal set is:", min(codingal))

The maximum element present in codingal set is: 2020

  1. sum()

The arithmetic sum of each item in a set is returned by the sum() method in the Python set module.

Example:

codingal=(2020, 2021, 2022, 2023)
print("The maximum element present in codingal set is:", sum(codingal))

The maximum element present in codingal set is: 8086

It cannot, however, be used to a set of strings.

Example:

codingal=('kids', 'love', 'codingal')
print("The maximum element present in codingal set is:", sum(codingal))

Traceback (most recent call last):

File "main.py", line 2, in <module>

print("The ma

ximum element present in codingal set is:", sum(codingal))

TypeError: unsupported operand type(s) for +: 'int' and 'str'

  1. any()

This method returns True even if one element in the set has a Boolean value of True.

Example:

codingal=('kids', 'love', 'codingal')
print("The element present in codingal set is:", any(codingal))

The element present in codingal set is: True

  1. all()

Unlike the any() method, the Python set’s all() function only returns True if every item in it has a Boolean value of True. Otherwise, False is returned.

Example:

codingal=('kids', 'love', 'codingal')
print("The element present in codingal set is:", all(codingal))

The element present in codingal set is: True

  1. sorted()

The sorted() method returns a sorted Python set to list. It is arranged in ascending order, but the initial set is unaffected.

Example:

codingal=(2022, 2023, 2021, 2020)
print("The sorted elements in codingal set is:", sorted(codingal))

The sorted elements in codingal set is: [2020, 2021, 2022, 2023]

 

Python methods on sets

A method in Python can change a set, in contrast to a function. It must be called on in order to conduct a series of operations on a set.

  1. Union()

This technique combines two or more Python sets using the union operator. It just returns every item that is a part of any of those sets.

Example:

# Create the two sets of two guest lists
set1 = {'A', 'B', 'C', 'D', 'E'}
set2 = {'B', 'D', 'V', 'X', 'Y', 'Z'}
# Find union of two sets
union = set1.union(set2)
# Converting set into list to find total guests to be invited in party
total_guests = list(union)
print("Total guests to be invited in party are :", len(total_guests))
print("Guest List :", total_guests)

Total guests to be invited in party are : 9

Guest List : ['Y', 'Z', 'B', 'X', 'D', 'C', 'V', 'E', 'A']

  1. Intersection()

The common elements in all the sets are returned by this function, which accepts sets as an input.

Example:

setx = {"green", "blue"}
sety = {"blue", "yellow"}
print("Original set elements:")
print(setx)
print(sety)
print("\nIntersection of two said sets:")
setz = setx.intersection(sety)
print(setz)

Original set elements:

{'blue', 'green'}

{'blue', 'yellow'}

Intersection of two said sets:

{'blue'}

  1. difference()

The difference between two or more sets is returned by the difference() function. It gives back a set.

Example:

# Create the two sets of two guest lists
set1 = {'A', 'B', 'C', 'D', 'E'}
set2 = {'B', 'D', 'V', 'X', 'Y', 'Z'}
# Find difference of two sets
a = set1.difference(set2)
print(“The difference of set1 and set 2 is:”,a)

The difference of set1 and set 2 is:{'C', 'A', 'E'}

  1. symmetric_difference()

All the elements specific to each set are returned by this method.

Example:

# Create the two sets of two guest lists
set1 = {'A', 'B', 'C', 'D', 'E'}
set2 = {'B', 'D', 'V', 'X', 'Y', 'Z'}
# Find symmetric_difference of two sets
a = set1.symmetric_difference(set2)
print("The Symmetric_difference of set1 and set 2 is:",a)

The Symmetric_difference of set1 and set 2 is: {'Y', 'Z', 'X', 'E', 'C', 'V', 'A'}

  1. copy()

A shallow copy of the Python set is made by the copy() method.

Example:

# Create the two sets of two guest lists
set1 = {'A', 'B', 'C', 'D', 'E'}
a = set1.copy()
print("The copy of set1 is:",set1,a)

The copy of set1 is: {'B', 'D', 'E', 'C', 'A'} {'B', 'D', 'C', 'E', 'A'}

  1. isdisjoint()

If there is a null intersection between two sets, this function returns True.

Example:

# Create the two sets of two guest lists
set1 = {'A', 'B', 'C', 'D', 'E'}
set2 = {'B', 'D', 'V', 'X', 'Y', 'Z'}
# Find isdisjoint of two sets
a = set1.isdisjoint(set2)
print("The isdisjoint of set1 and set 2 is:",a)

The isdisjoint of set1 and set 2 is: False

  1. issubset()

If the set in the argument includes this set, this method returns true.

Example:

# Create the two sets of two guest lists
set1 = {'A', 'B', 'C', 'D', 'E'}
set2 = {'B', 'D', 'V', 'X', 'Y', 'Z'}
# Find issubset of two sets
a = set1.issubset(set2)
print("The issubset of set1 and set 2 is:",a)

The issubset of set1 and set 2 is: False

  1. issuperset()
# Create the two sets of two guest lists
set1 = {'A', 'B', 'C', 'D', 'E'}
set2 = {'B', 'D', 'V', 'X', 'Y', 'Z'}
# Find issuperset of two sets
a = set1.issuperset(set2)
print("The issuperset of set1 and set 2 is:",a)

The issuperset of set1 and set 2 is: False

Conclusion

As we have seen, a Python Boolean value can either be True or False. When it is returned by a method, you we are allowed to create it or use it. A set’s creation, use, updating, and deletion have all been covered.

We already learned that it is mutable, which is why we are unable to access, edit, or remove it via indexing. In order to do this, we employ certain Python set functions and methods.

The several operations we may use on a set were the last thing we learned about.

Python for kids can open up a lot of career options for kids in the future. With many advanced fields using Python, a lot of career opportunities have opened up now and will continue to do so in the future.

Many popular web applications such as YouTube, Instagram and the most popular search engine Google use Python for web development. It is used in many fields and is expected to continue to do so.

Python knowledge can open up a lot of career options for your kid in the future.

Sign up to our newsletter

Get the latest blogs, articles, and updates delivered straight to your inbox.

Share with your friends

Try a free class