Python Sets
A set is a collection of unique, unordered items. Python sets are used to store multiple elements in a single variable without duplicates. Sets are highly optimized for membership testing and removing duplicate entries from a sequence. Sets are written using curly braces {}
.
Definition and Characteristics of Sets
- Unordered: Sets do not record element position or order of insertion. Elements are stored in an unpredictable order.
- Mutable: Although sets themselves are mutable (i.e., elements can be added or removed), they can only contain immutable elements like numbers, strings, or tuples.
- Unique Elements: A set cannot have duplicate elements. Adding a duplicate element has no effect.
- No Indexing or Slicing: You cannot access set elements using indices like lists or tuples.
Let's see how to create a basic set in Python:
Example 1: Creating a Set
# Example: Creating a Set
my_set = {1, 2, 3, 4, 5}
print("Set:", my_set)
Output
Sets can contain elements of different data types, including integers, strings, and floats:
Example 2: Set with Mixed Data Types
# Example: Set with Mixed Data Types
mixed_set = {1, "apple", 3.14, True}
print("Mixed Set:", mixed_set)
Output
Note that the output does not show True as 1 because sets do not allow duplicate values, and True
is treated as 1 in Python.
Basic Set Operations
Python sets support various mathematical set operations like union, intersection, difference, and symmetric difference.
Let's see how to perform these operations:
Example 3: Set Operations
# Example: Set Operations
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
# Union
print("Union:", A | B)
# Intersection
print("Intersection:", A & B)
# Difference
print("Difference:", A - B)
# Symmetric Difference
print("Symmetric Difference:", A ^ B)
Output
Explanation:
- Union (|
): Combines elements from both sets, excluding duplicates.
- Intersection (&
): Returns only elements found in both sets.
- Difference (-
): Elements present in the first set but not in the second.
- Symmetric Difference (^
): Elements in either set but not in both.
Common Set Methods
Python sets provide several built-in methods:
add(item)
: Adds an item to the set.remove(item)
: Removes the specified item. Raises an error if the item is not found.discard(item)
: Removes the specified item without raising an error if the item is not found.pop()
: Removes and returns an arbitrary item from the set.clear()
: Removes all items from the set.copy()
: Returns a shallow copy of the set.
Here are some examples of using these methods:
Example 4: Using Set Methods
# Example: Using Set Methods
fruits = {"apple", "banana", "cherry"}
# Add an item
fruits.add("orange")
print("After add:", fruits)
# Remove an item
fruits.remove("banana")
print("After remove:", fruits)
# Discard an item (no error if not found)
fruits.discard("pineapple")
print("After discard:", fruits)
# Pop an item
item = fruits.pop()
print("Popped item:", item)
print("Set after pop:", fruits)
# Clear the set
fruits.clear()
print("After clear:", fruits)
Output
Frozen Sets
Frozen sets are immutable versions of Python sets. Once a frozen set is created, you cannot modify it (i.e., no adding or removing elements). Frozen sets are useful when you need a constant set that remains unchanged.
Here’s an example of how frozen sets work:
Example 5: Frozen Sets
# Example: Creating a Frozen Set
frozen_set = frozenset([1, 2, 3, 4, 5])
print("Frozen Set:", frozen_set)
# Trying to add an element to a frozen set (will raise an error)
try:
frozen_set.add(6)
except AttributeError as e:
print("Error:", e)