Sets are an unordered collection of unique items in Python. Set data type are useful for storing and manipulating collections of items where duplicate items are not allowed. Python provides several methods for working with sets, and in this article, we will discuss some of the most commonly used set methods.
1) set.add(): This method adds an item to a set.
For example:
a = {1, 2, 3, 4, 5} a.add(6) print(a) # Output: {1, 2, 3, 4, 5, 6}
2) set.update(): This method adds multiple items in one go to a set.
For example:
a = {1, 2, 3, 4, 5} a.update([6, 7, 8]) print(a) # Output: {1, 2, 3, 4, 5, 6, 7, 8}
3) set.remove(): This method removes a specified item from a set. If the item is not found in the set then a KeyError is raised.
For example:
a = {1, 2, 3, 4, 5} a.remove(3) print(a) # Output: {1, 2, 4, 5}
4) set.discard(): This method removes a specified item from a set, but does not raise an error even if the item is not found in the set.
For example:
a = {1, 2, 3, 4, 5} a.discard(3) print(a) # Output: {1, 2, 4, 5}
5) set.pop(): This method removes random item and return that item from a set.
For example:
a = {1, 2, 3, 4, 5} print(a.pop()) # Output: 1 print(a) # Output: {2, 3, 4, 5}
6) set.clear(): This method remove all items from a set in a one go.
For example:
a = {1, 2, 3, 4, 5} a.clear() print(a) # Output: set()
7) len(): This is built-in function which returns the number of items in a set.
For example:
a = {1, 2, 3, 4, 5} print(len(a)) # Output: 5
In conclusion, these are some of the most commonly used set methods in Python. Sets provide a flexible and efficient way to store and manipulate collections of distinct items. By understanding and using these methods, we can effectively work with Set data type in Python.