In Python, the set() function is used to create a mutable, unordered collection of unique elements.
Function Syntax
set([iterable])
Parameter:
iterable: Any iterable object; creates an empty set if omitted.
Returns a set object.
Set
A set is an unordered, non-repeating data structure in Python, implemented based on a hash table.
Creating Sets
Using the set() function to create a set:
# Create from a list
lst = set(["a", "b", "c"])
print(lst) # {'a', 'b', 'c'}
# Create from a tuple
numbers = set((1, 2, 3, 2, 1))
print(numbers) # {1, 2, 3}
# Create from a string
chars = set("hello")
print(chars) # {'e', 'h', 'l', 'o'}
# Create from a range
range_set = set(range(5))
print(range_set) # {0, 1, 2, 3, 4}
# Create from a dictionary (only keys are taken)
dict_set = set({"a": 1, "b": 2})
print(dict_set) # {'a', 'b'}
You can also use curly braces {} to create a non-empty set:
# Create a set with elements
set1 = {"a", "b", "c"}
print(set1) # {'a', 'b', 'c'}
# Using comprehension
set2 = {x for x in range(5)}
print(set2) # {0, 1, 2, 3, 4}
# Cannot use {} to create an empty set
empty_set = {} # This is a dictionary, not a set
print(type(empty_set)) # <class 'dict'>
# Correct way to create an empty set
empty_set = set()
print(type(empty_set)) # <class 'set'>
Characteristics of Sets
Set elements are unordered, unique, and hashable.
# Unordered, output may vary each run
print(set('hello')) # {'e', 'l', 'h', 'o'}
# Unique, automatically deduplicates
print(set([1,1,1])) # {1}
# Hashable, elements must be immutable
s = {123,"hello",(1,2,3)} # {123, 'hello', (1, 2, 3)}
print(s)
# s = {[]} # TypeError
Basic Set Operations
s = {1, 2, 3}
# Add element
s.add(4)
s.add(2)
print(s) # {1, 2, 3, 4}
# Remove element
s.remove(3)
print(s) # {1, 2, 4}
# Removing a non-existent element raises an error
try:
s.remove(5)
except KeyError as e:
print(f"KeyError: {e}")
# Safe removal, no error
s.discard(5)
s.discard(2)
print(s) # {1, 4}
# Pop an element (random)
popped = s.pop()
# Clear the set
s.clear()
print(s) # set()
# Check if element exists
s = {1, 2, 3}
print(2 in s) # True
print(5 in s) # False
Set Operations
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# Union
print(A | B)
print(A.union(B))
# Intersection
print(A & B)
print(A.intersection(B))
# Difference (elements in A but not in B)
print(A - B)
print(A.difference(B))
# Symmetric Difference (elements in either A or B, but not in both)
print(A^B)
print(A.symmetric_difference(B))
Set Relationship Checks
X = {1, 2, 3}
Y = {1, 2}
Z = {3, 4}
# Subset check
print(f"Y ⊆ X? {Y.issubset(X)}") # True
print(f"Y <= X? {Y <= X}") # True
# Proper subset check
print(f"Y ⊂ X? {Y < X}") # True (Y is a proper subset of X)
# Superset check
print(f"X ⊇ Y? {X.issuperset(Y)}") # True
print(f"X >= Y? {X >= Y}") # True
# Proper superset check
print(f"X ⊃ Y? {X > Y}") # True
# Disjoint check
print(f"X ∩ Z = ∅? {X.isdisjoint(Z)}") # False (has intersection 3)
print(f"Y ∩ Z = ∅? {Y.isdisjoint(Z)}") # True (no intersection)
Set Modification Operations
A = {1, 2, 3}
B = {3, 4, 5}
# Add multiple elements
A.update([4, 5, 6])
# Intersection update (keep only common elements)
A = {1, 2, 3}
A.intersection_update(B)
# Difference update (remove elements also in B)
A = {1, 2, 3, 4}
A.difference_update(B)
# Symmetric difference update
A = {1, 2, 3}
A.symmetric_difference_update(B)
Practical Set Methods
s = {1, 2, 3}
# Copy the set
shallow_copy = s.copy()
# Length of the set
length = len(s)
# Iterate over the set
for item in s:
print(item)