Useful set functions in Python
The previous article introduced the concept of sets. This article explores useful set functions associated with accessing, adding and removing elements from a set. Some of these are the same as used for manipulating lists, while others are unique to only sets.
Determining the length of a set
The length of a set is the total number of elements in a set. The syntax to determine the length of a set is len(set)
. This function is also used to determine the lengths of strings and lists.
a = {1,2,3,4,5}
print(len(a))
#OUTPUT 5
Checking membership in a set
Checking membership in a set is a conditional method to determine whether a specific element occurs in a set. There are 2 operators; element in set
and element not in set
to check the occurrence of an element in a set.
a = {1,2,3,4,5}
print(3 in a)
#OUTPUT True
a = {1,2,3,4,5}
print(6 not in a)
#OUTPUT True
Two set functions to add new elements
New elements can be added to sets using the syntax set.add(newElement)
.
a = {1,2,3,4,5}
a.add(6)
print(a)
#OUTPUT {1, 2, 3, 4, 5, 6}
The set.add()
adds only one element to a set at a time. Multiple elements cannot be added with this function.
To add multiple elements use set.update()
a = {1,2,3,4,5}
a.update({6,7,8})
print(a)
#OUTPUT {1, 2, 3, 4, 5, 6, 7, 8}
Similarly, other data types such as strings, lists, tuples and dictionaries can also be added. There is no need of converting other data types to sets in order to use this function.
Three set functions to eliminate set elements
The set.clear()
function is used to remove all the elements from a set.
a = {1,2,3,4,5}
a.clear()
print(a)
#OUTPUT set()
To clear specific elements from a set use set.discard(element)
a = {1,2,3,4,5}
a.discard(5)
print(a)
#OUTPUT {1, 2, 3, 4}
Similarly, set.remove(element)
can also be used to eliminate set elements.
a = {1,2,3,4,5}
a.remove(5)
print(a)
#OUTPUT {1, 2, 3, 4}
set.remove(element)
method will throw an error and exit if the element does not exist in the set. Whereas, set.discard(element)
will proceed to the next line without throwing an error.
Discuss