Unique Values , Adding & Removing Elements in Set
-
This lesson teaches how Python sets ensure that all elements are unique.
Creating a Set
numbers = {10, 20, 30, 40}
print(numbers)
Code Description
A set named numbers is created with four values.
All elements are stored only once.
Duplicate Values are Removed Automatically
Set Removes Duplicates
data = {1, 2, 2, 3, 4, 4, 5}
print(data)
Code Description
Even though 2 and 4 are repeated, the set stores them only once.
Using set() Constructor
items = set([1, 2, 3, 3, 4])
print(items)
Code Description
List converted into a set. Duplicate values removed.
Accessing Set Values
A set does not support indexing because it is an unordered collection.
So, you cannot access elements by position like set[0].
Loop Through Set
colors = {"red", "blue", "green"}
for color in colors:
print(color)
Code Description
We use a loop to access values because sets are unordered.
add() Method
The add() method is used to add a single element to a set.
fruits = {"apple", "banana", "mango"}
fruits.add("orange")
print(fruits)
Explanation
Adds only one item at a time
If item already exists, nothing changes
Set automatically avoids duplicates
update() Method
The update() method adds multiple elements to a set.
numbers = {1, 2, 3}
numbers.update([4, 5, 6])
print(numbers)
Explanation
Can add list, tuple, or another set
Adds many items at once
remove() Method
The remove() method removes a specific element.
fruits = {"apple", "banana", "mango"}
fruits.remove("banana")
print(fruits)
Explanation
✔ Removes specified item
❌ Gives error if item not found
discard() Method
The discard() method removes an element safely.
fruits = {"apple", "banana", "mango"}
fruits.discard("banana")
fruits.discard("grapes") # no error
print(fruits)
Explanation
No error if item does not exist
Safer than remove()
pop() Method
The pop() method removes a random element from the set.
fruits = {"apple", "banana", "mango"}
removed_item = fruits.pop()
print("Removed:", removed_item)
print(fruits)
Explanation
Removes random item
Useful when order doesn't matter
clear() Method
The clear() method removes all elements from the set.
fruits = {"apple", "banana", "mango"}
fruits.clear()
print(fruits)
Explanation
Set becomes empty
Set still exists