Sets
In Python, a set is an unordered collection of unique elements. Sets are often used when you need to store a collection of distinct items. This section covers the basics of sets and common set operations.
1. Creating Sets
You can create a set by enclosing elements in curly braces {}
and separating them with commas.
fruits = {"apple", "banana", "cherry"}
Alternatively, you can use the set()
constructor and pass an iterable like a list or tuple.
colors = set(["red", "green", "blue"])
2. Accessing Set Elements
Sets are unordered, so you cannot access elements by index as you can with lists or tuples. Instead, you can check for the existence of an element using the in
keyword.
fruits = {"apple", "banana", "cherry"}
has_apple = "apple" in fruits # Check if "apple" exists in the set
3. Modifying Sets
Sets are mutable, meaning you can add and remove elements from them.
To add an element, use the add()
method.
fruits = {"apple", "banana", "cherry"}
fruits.add("orange") # Add "orange" to the set
To remove an element, use the remove()
method. If the element is not in the set, this method will raise a KeyError
.
fruits.remove("banana") # Remove "banana" from the set
To safely remove an element, use the discard()
method. It will not raise an error if the element is not found.
fruits.discard("strawberry") # Safely remove "strawberry" (if it exists)
4. Set Operations
Sets support various set operations, such as union, intersection, difference, and symmetric difference.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2 # Union of sets (combines elements)
intersection_set = set1 & set2 # Intersection of sets (common elements)
difference_set = set1 - set2 # Difference of sets (elements in set1 but not in set2)
symmetric_difference_set = set1 ^ set2 # Symmetric difference (elements in either set, but not both)
5. Iterating Over Sets
You can loop through the elements in a set using a for
loop.
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
Sets are often used when you need to maintain a collection of distinct items or perform set operations like finding common elements between two sets.