A set in Python is an unordered, mutable, and unique collection of elements. It is similar to a list, but it does not allow duplicate values and is optimized for fast lookups.
my_set = {1, 2, 3, 4, 5} # Defining a set
empty_set = set() # Creating an empty set (NOT {})
Important: {}
creates an empty dictionary, not an empty set.
Feature | Set (set ) |
List (list ) |
---|---|---|
Order | Unordered | Ordered |
Duplicates | No duplicates allowed | Duplicates allowed |
Mutability | Mutable (can add/remove elements) | Mutable |
Indexing | No indexing (cannot access elements by position) | Supports indexing |
Performance | Faster for membership tests (in operator) |
Slower for membership tests |
Use Case | Unique elements, fast lookups, set operations | Ordered collections, duplicates allowed |
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_set = set(my_list) # Removes duplicates
print(unique_set) # Output: {1, 2, 3, 4, 5}
* Sets are useful for removing duplicates from lists.
my_set = {1, 2, 3}
# Add an element
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
# Remove an element
my_set.remove(2)
print(my_set) # Output: {1, 3, 4}
# Discard (won't raise an error if the element is missing)
my_set.discard(10) # No error
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
# Union (A ∪ B): Combines both sets
print(A | B) # Output: {1, 2, 3, 4, 5, 6}
# Intersection (A ∩ B): Common elements
print(A & B) # Output: {3, 4}
# Difference (A - B): Elements in A but not in B
print(A - B) # Output: {1, 2}
# Symmetric Difference (A ⊕ B): Elements in either A or B, but not both
print(A ^ B) # Output: {1, 2, 5, 6}
* Sets are powerful for mathematical operations and fast lookups.
x in my_set
is faster than x in my_list
).