Introduction
Python sets are collections of unique elements, which means they automatically eliminate duplicate entries. Sets provide a variety of methods for performing mathematical set operations and other useful functionalities. Below is a comprehensive guide to the commonly used set methods with brief examples.
1. add(element)
Adds an element to the set.
s = {1, 2, 3}
s.add(4) # {1, 2, 3, 4}
2. clear()
Removes all elements from the set.
s = {1, 2, 3}
s.clear() # set()
3. copy()
Returns a shallow copy of the set.
s = {1, 2, 3}
new_s = s.copy() # {1, 2, 3}
4. discard(element)
Removes an element from the set if it is present. Does nothing if the element is not found.
s = {1, 2, 3}
s.discard(2) # {1, 3}
s.discard(4) # {1, 3} (No error)
5. remove(element)
Removes an element from the set. Raises a KeyError
if the element is not found.
s = {1, 2, 3}
s.remove(2) # {1, 3}
# s.remove(4) # Raises KeyError
6. pop()
Removes and returns an arbitrary element from the set. Raises a KeyError
if the set is empty.
s = {1, 2, 3}
element = s.pop() # 1 (or any element, set is unordered)
7. update(iterable)
Adds all elements from an iterable to the set.
s = {1, 2}
s.update([3, 4]) # {1, 2, 3, 4}
8. union(set)
Returns a new set with all elements from the set and the specified set.
s1 = {1, 2}
s2 = {2, 3}
s3 = s1.union(s2) # {1, 2, 3}
9. intersection(set)
Returns a new set with elements common to both sets.
s1 = {1, 2, 3}
s2 = {2, 3, 4}
s3 = s1.intersection(s2) # {2, 3}
10. difference(set)
Returns a new set with elements in the set that are not in the specified set.
s1 = {1, 2, 3}
s2 = {2, 3, 4}
s3 = s1.difference(s2) # {1}
11. symmetric_difference(set)
Returns a new set with elements in either set but not in both.
s1 = {1, 2, 3}
s2 = {2, 3, 4}
s3 = s1.symmetric_difference(s2) # {1, 4}
12. issubset(set)
Returns True
if all elements of the set are in the specified set.
s1 = {1, 2}
s2 = {1, 2, 3}
s1.issubset(s2) # True
13. issuperset(set)
Returns True
if all elements of the specified set are in the set.
s1 = {1, 2, 3}
s2 = {1, 2}
s1.issuperset(s2) # True
14. isdisjoint(set)
Returns True
if the set has no elements in common with the specified set.
s1 = {1, 2}
s2 = {3, 4}
s1.isdisjoint(s2) # True
Conclusion
Python sets offer a range of methods to handle unique elements and perform various set operations efficiently. From adding and removing elements to performing union, intersection, and difference operations, these methods provide essential tools for working with sets in Python.
Top comments (0)