Python Set Methods
Sets in Python are unordered collections of unique elements. Python provides several methods to work with sets, many of which are useful for mathematical operations like union, intersection, and difference.
Common Set Methods
add()
: Adds an element to the set.remove()
: Removes a specified element from the set. Raises aKeyError
if the element is not found.discard()
: Removes a specified element from the set if it is present.union()
: Returns a new set containing all elements from both sets.intersection()
: Returns a new set containing only the elements found in both sets.difference()
: Returns a new set containing elements found in the first set but not in the second.issubset()
: ReturnsTrue
if all elements of the set are contained in another set.
Example Usage
Python
# Example of using set methods
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1.union(set2)) # {1, 2, 3, 4}
print(set1.intersection(set2)) # {2, 3}
print(set1.difference(set2)) # {1}
Import Links
Here are some useful import links for further reading: