Data Structures
Python Set Methods
Python Set Methods
Python set methods like add and union handle unique elements.
Introduction to Python Sets
Python sets are an unordered collection of unique elements. They are mutable, meaning you can add or remove items from them. Sets are particularly useful for operations involving membership checks, duplicates elimination, and mathematical operations like unions and intersections.
Creating a Set
You can create a set by using curly braces {}
or the set()
constructor.
Adding Elements to a Set
To add elements to a set, you can use the add()
method. It adds a single element to the set.
Removing Elements from a Set
Python provides several methods for removing elements from a set: remove()
and discard()
. The remove()
method raises a KeyError
if the element is not found, while discard()
does not.
Set Union Operation
The union()
method returns a new set containing all unique elements from both sets. It can also be performed using the |
operator.
Set Intersection Operation
The intersection()
method returns a new set containing only elements that are present in both sets. It can also be performed using the &
operator.
Set Difference Operation
The difference()
method returns a new set containing elements that are in the first set but not in the second. You can also use the -
operator for this operation.
Conclusion
Sets in Python offer a powerful way to handle collections of unique items with efficient operations for membership testing and mathematical set operations. Mastering these methods enables you to manage data more effectively and perform complex queries with ease.
Data Structures
- Previous
- Dictionary Methods
- Next
- Tuple Methods