Python sets are a versatile data structure that allow you to store multiple unique elements in an unordered collection.
What is a Python Set?
A set in Python is an unordered collection of unique items. Unlike lists and tuples, sets do not allow duplicate elements and their elements are not stored in any specific order.
Key Features of Sets:
- Unordered: The elements in a set do not maintain any particular order.
- Unique Items: Sets automatically remove duplicate items.
- Mutable: You can add or remove elements from a set after its creation.
- Unindexed: Sets do not support indexing or slicing.
How to Create a Python Set?
You can create a set using curly braces { } or the built-in set( ) function.
Syntax:
set_name = {item1, item2, item3, ...}
Examples:
# Creating a set of integers
numbers = {1, 2, 3, 4}
# Creating a set of strings
fruits = {"apple", "banana", "cherry"}
# Using the set() function
empty_set = set() # Creates an empty set
Note: Using { } without elements creates an empty dictionary, not a set. Use set() to create an empty set.
Characteristics of Python Sets
Automatic Deduplication:
Sets eliminate duplicate values automatically.
data = {1, 2, 2, 3}
print(data) # Output: {1, 2, 3}
Hashable Elements:
Only immutable and hashable elements (like numbers, strings and tuples) can be added to a set.
No Duplicates Allowed:
Sets are useful for maintaining unique collections of items.
Accessing Elements in a Set
Since sets are unordered and unindexed, you cannot access their elements directly using indices. Instead, you use loops or membership operators.
Examples:
fruits = {"apple", "banana", "cherry"}
# Check if an item exists
print("apple" in fruits) # Output: True
# Iterate through the set
for fruit in fruits:
print(fruit)
Set Methods and Operations
Python provides several built-in methods and operations to work with sets effectively.
1. Adding and Removing Elements:
Method | Description |
---|---|
add(item) | Adds a single item to the set. |
update(iterable) | Adds multiple items from an iterable (e.g., list, tuple). |
remove(item) | Removes an item. Raises an error if not found. |
disc ard(item) | Removes an item. Does not raise an error if not found. |
pop() | Removes and returns a random item. |
clear() | Removes all elements from the set. |
Examples:
# Adding elements
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits) # Output: {"apple", "banana", "cherry"}
# Removing elements
fruits.remove("banana")
print(fruits) # Output: {"apple", "cherry"}
# Removing a random element
random_item = fruits.pop()
print(random_item) # Output: "apple" (or "cherry")
2. Set Operations:
Sets support mathematical operations like union, intersection, difference and symmetric difference.
Operation | Syntax | Description |
---|---|---|
Union | `set1 | set2` |
Intersection | set1 & set2 | Common elements between both sets. |
Difference | set1 – set2 | Elements in set1 but not in set2. |
Symmetric Difference | set1 ^ set2 | Elements in either set, but not both. |
Examples:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Union
print(set1 | set2) # Output: {1, 2, 3, 4, 5}
# Intersection
print(set1 & set2) # Output: {3}
# Difference
print(set1 - set2) # Output: {1, 2}
# Symmetric Difference
print(set1 ^ set2) # Output: {1, 2, 4, 5}
3. Membership Tests:
Check if an element exists in a set using the in and not in keywords.
Example:
fruits = {"apple", "banana", "cherry"}
print("apple" in fruits) # Output: True
print("orange" not in fruits) # Output: True
4. Copying a Set:
Create a copy of a set using the copy() method.
original = {1, 2, 3}
copy_set = original.copy()
print(copy_set) # Output: {1, 2, 3}
Frozenset: Immutable Sets
A frozenset is an immutable version of a set. Once created, its elements cannot be changed.
Example:
frozen = frozenset([1, 2, 3])
print(frozen) # Output: frozenset({1, 2, 3})