(toc)
A set in Python is a collection data type that is unordered, mutable, and does not allow duplicate elements. Sets are useful for operations involving unique items, such as membership tests, removing duplicates, and performing mathematical set operations like union and intersection.
Key Features of Sets
- Unordered: The elements in a set have no specific order.
- No Duplicates: Sets automatically remove duplicate elements.
- Mutable: You can add or remove elements, but the elements themselves must be immutable (e.g., numbers, strings, or tuples).
Creating Sets
You can create a set using curly braces {}
or the set()
constructor.
Examples:
# Creating sets fruits = {"apple", "banana", "cherry"} numbers = set([1, 2, 3, 4, 5]) # Empty set (must use set(), not {}) empty_set = set() print(fruits) # Output: {'apple', 'cherry', 'banana'} print(numbers) # Output: {1, 2, 3, 4, 5} print(empty_set) # Output: set()
Accessing Set Elements
Since sets are unordered, you cannot access elements using an index. Instead, you can iterate through the set or use membership testing.
Example:
fruits = {"apple", "banana", "cherry"} # Membership testing print("apple" in fruits) # Output: True print("grape" in fruits) # Output: False # Iterating through a set for fruit in fruits: print(fruit)
Set Operations
Python provides several operations for working with sets, inspired by mathematical set theory.
-
Union (
|
orunion()
): Combines all unique elements from two sets.set1 = {1, 2, 3} set2 = {3, 4, 5} print(set1 | set2) # Output: {1, 2, 3, 4, 5} print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
-
Intersection (
&
orintersection()
): Returns only the elements common to both sets.print(set1 & set2) # Output: {3} print(set1.intersection(set2)) # Output: {3}
-
Difference (
-
ordifference()
): Returns elements present in one set but not in the other.print(set1 - set2) # Output: {1, 2} print(set1.difference(set2)) # Output: {1, 2}
-
Symmetric Difference (
^
orsymmetric_difference()
): Returns elements in either set but not in both.print(set1 ^ set2) # Output: {1, 2, 4, 5}
Modifying Sets
-
Adding Elements
Useadd()
to add a single element to a set.fruits = {"apple", "banana"} fruits.add("cherry") print(fruits) # Output: {'apple', 'banana', 'cherry'}
-
Updating with Multiple Elements
Useupdate()
to add multiple elements to a set.fruits.update(["grape", "orange"]) print(fruits) # Output: {'apple', 'banana', 'cherry', 'grape', 'orange'}
-
Removing Elements
remove(element)
: Removes an element, raises an error if it doesn’t exist.discard(element)
: Removes an element, does nothing if it doesn’t exist.pop()
: Removes and returns an arbitrary element.clear()
: Removes all elements from the set.
fruits = {"apple", "banana", "cherry"} fruits.remove("banana") # Raises an error if "banana" doesn't exist fruits.discard("grape") # Does nothing if "grape" doesn't exist popped = fruits.pop() # Removes an arbitrary element print(popped) fruits.clear() # Empties the set
Set Methods
Method | Description |
---|---|
add(element) |
Adds an element to the set. |
remove(element) |
Removes the specified element. Raises an error if missing. |
discard(element) |
Removes the specified element. Does nothing if missing. |
pop() |
Removes and returns an arbitrary element. |
clear() |
Removes all elements from the set. |
union(other_set) |
Returns the union of two sets. |
intersection(other_set) |
Returns the intersection of two sets. |
difference(other_set) |
Returns the difference of two sets. |
symmetric_difference() |
Returns the symmetric difference of two sets. |
Frozen Sets
A frozen set is an immutable version of a set. You can create a frozen set using the frozenset()
function.
Example:
frozen = frozenset([1, 2, 3]) print(frozen) # Output: frozenset({1, 2, 3}) # Frozen sets are immutable # frozen.add(4) # This will raise an AttributeError
Use Cases of Sets
-
Removing Duplicates from a List
numbers = [1, 2, 2, 3, 4, 4, 5] unique_numbers = set(numbers) print(unique_numbers) # Output: {1, 2, 3, 4, 5}
-
Membership Testing
Sets are optimized for fast membership testing.words = {"hello", "world", "python"} print("python" in words) # Output: True
-
Mathematical Set Operations
Use sets for tasks like finding common elements or differences between groups. -
Filtering Data
Use sets to remove duplicates or filter data efficiently.