Basic Set Operations in Python
Set Operations in Python
Python Sets are another data structure, basically, it is the same as lists but it has no duplicate entries. Technically, a set is a mutable and unordered collection of items which means that we can easily add or remove items for it.
Creating a set
A set is created by placing all the elements inside curly brackets{}, separated by using the built-in function set(). It has the following syntax:
set_variable={value1, value2,...}
Example :
x={1,2,3,4,5,"SRK"} print(x)
Output:
{1, 2, 3, 4, 5, 'SRK'}
Set Operation | Description |
s.update(t) | It adds elements of set t in the set s provided that all duplicates are avoided. |
s.add(x) | It adds elements x to the set s provided that all duplicates are avoided. |
s.remove(x) | It removes element x from set s and returns KeyError if x isn't present. |
s.discard(x) | It removes element x from set s but it doesn't give an error if x is not present in the set. |
s.pop() | It removes and returns an arbitrary element from s |
s.clear() | It removes all elements from the set. |
len(s) | It returns the length of set. |
x in s | It returns True is x is present in set s and False otherwise. |
x not in s | It returns True is x is not present in set s and False otherwise. |
s.issubnet(t) | It returns True if every element in set s is present in set t and False otherwise. |
s.issuperset(t) | It returns True if every element in the set t is present in set s and False otherwise. |
s.union(t) | It returns a set s that has elements from both sets s and t. |
s.intersection(t) | It returns a new set that has elements which are common to both the sets s and t. |
s.intersection_update(t) | It returns a set that has elements which are common to both the sets s and t. |
s.difference(t) | It returns a new set that has elements in set s but not in t. |
s.difference_update(t) | It removes all elements of another set from this set. |
s.symmetri_difference(t) | It returns a new set with elements either in s or in t but not both. |
s.copy() | It returns a copy of set s |
s.isisjoint(t) | It returns True if two sets have a null intersection. |
all(s) | It returns True if all elements in the set are True and False otherwise. |
any(s) | It returns True if any of the elements in the set is True, returns False if the set is empty. |
enumerate(s) | It returns an enumerate object which contains index as well as the value of all the items of the set as a pair. |
max(s) | It returns the maximum value in a set. |
min(s) | It returns the minimum value in a set. |
sum(s) | It returns the sum of elements in the set. |
sorted(s) | It returns a new sorted list from elements in the set. It doesn't sort the set as sets are immutable. |
s==t and s!=t | s==t returns True if the two sets are equivalent and False otherwise. |