Python Programming Language have some built-in functions which can be applied to Sets. Despite these there does exist some Set Methods and Set Operations which can be performed on Python Sets.
Below is a list of all these built-in Python Set Functions.
- all()
- any()
- enumerate()
- len()
- max()
- min()
- sorted()
- sum()
Let’s discuss each one of these functions one by one.
Table of Contents
Using all() function for Sets
Returns True only if all elements in Set are true, false otherwise.
# Example
set1 = {29, 172, 18}
all(set1) # Returns True
Using any() function for Sets
Returns True if any element of the set is True, false if set is empty.
# Example
set1 = {727, 982, 10}
all(set1) # Returns True
set2 = {}
all(set2) # Returns False
Using enumerate() function for Sets
Returns an enumerate object. It contains the index and value for all the items of the set as a pair.
# Example
set1 = {18, 19, 63, 15}
enumerate(set1) # Changes set1 to an enumerate object
Using len() function for Sets
len() function returns length of set/number of elements in a Set.
# Example
set1 = {17, 25, 67, 14, 65}
len(set1) # Returns 5 as there are five elements in set1
Using max() function for Sets
max() function returns largest value item from a Set.
# Example
set1 = {28, 73, 189}
max(set1) # Returns 189 as its largest element in set1
set2 = {"Hello", "How are you"}
max(set2) # Returns "How are you"
Using min() function for Sets
min() is opposite to max() as this returns minimum value item from Set.
# Example
set1 = {28, 73, 189}
max(set1) # Returns 28 as its smallest element in set1
set2 = {"Hello", "How are you"}
max(set2) # Returns "Hello"
Using sorted() function for Sets
sorted() function returns a list containing elements of Set in sorted order. This function doesn’t sort set itself rather it makes of list copy of Set first, sort it and then return.
# Example
set1 = {72, 91, 28, 23}
sorted(set1) # Returns [23, 28, 73, 91] list
Using sum() function for Sets
sum() function will return sum of all elements inside set, if and only if elements inside can be added together. But if elements inside set cann’t be added together(Elements are strings only) then python will raise TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’ error.
# Example
set1 = {29, 18, 34}
sum(set1) # Returns 81
No Comments
Leave a comment Cancel