A set is a built-in Python data type used to store unordered, unique elements.
Unordered → Elements have no fixed order.
Unique → No duplicate values are allowed.
Mutable → You can add or remove elements, but elements themselves must be immutable (like numbers, strings, tuples — but not lists or dictionaries).
2. Creating a Set
# Empty set
my_set = set()
# Set with values
fruits = {"apple", "banana", "cherry"}
print(fruits) # {'apple', 'banana', 'cherry'}
# Duplicates are ignored
nums = {1, 2, 2, 3, 4}
print(nums) # {1, 2, 3, 4}
{} creates an empty dictionary, not a set. Always use
set() for an empty set.
3. Accessing Elements
Since sets are unordered, they don’t support indexing (set[0]). You loop through them:
for fruit in fruits:
print(fruit)
4. Adding & Removing Elements
fruits.add("orange") # Add single element
print(fruits)
fruits.update(["grape", "mango"]) # Add multiple elements
print(fruits)
fruits.remove("banana") # Removes element (raises error if not found)
fruits.discard("pear") # Removes element (NO error if not found)
fruits.pop() # Removes a random element
fruits.clear() # Removes all elements
5. Set Operations
Sets are powerful for mathematical operations:
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B) # Union → {1, 2, 3, 4, 5, 6}
print(A & B) # Intersection → {3, 4}
print(A - B) # Difference → {1, 2}
print(A ^ B) # Symmetric Difference → {1, 2, 5, 6}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
1. What is a Set in Python?
2. Creating a Set
{}creates an empty dictionary, not a set. Always useset()for an empty set.3. Accessing Elements
Since sets are unordered, they don’t support indexing (
set[0]).You loop through them:
4. Adding & Removing Elements
5. Set Operations
Sets are powerful for mathematical operations:
6. Set Methods
7. Frozen Sets (Immutable Sets)
If you need an immutable set (cannot be changed):
8. Example Use Cases
Removing duplicates from a list:
Membership testing (faster than lists):
Summary: