element : element to be added to setmy_set={'Alex','Ronald','John'}
my_set.add('Lewis')
print(my_set)
Output is here
{'Ronald', 'John', 'Alex', 'Lewis'}
Adding duplicate value
my_set={'a','b','c','x'}
my_set.add('c')
print(my_set)
Output
{'a', 'x', 'c', 'b'}
There is no error if we try to add element already available but it will not add the element again as set can't have duplicate elements. unique_items = set()
for item in ['apple', 'banana', 'apple', 'orange']:
unique_items.add(item)
print(unique_items) # Output: {'banana', 'apple', 'orange'}
add(): Adds a single element to the set.
my_set = {1, 2}
my_set.add(3)
print(my_set) # Output: {1, 2, 3}
update(): Adds multiple elements from an iterable (e.g., list, tuple).
my_set = {1, 2}
my_set.update([3, 4, 5]) # Adds multiple elements
print(my_set) # Output: {1, 2, 3, 4, 5}
The add() method adds one element at a time, while update() can add several elements in one go.
my_set = {1, 2, 3}
# Add item only if it is greater than 10
item = 15
if item > 10:
my_set.add(item)
print(my_set)
{1, 2, 3, 15}
Sets are great for tracking unique items in a collection. For instance, let’s collect unique words from a list.
words = ["apple", "banana", "apple", "cherry", "banana", "date"]
unique_words = set()
for word in words:
unique_words.add(word)
print(unique_words)
{'apple', 'banana', 'cherry', 'date'}
We can use the union method or the | operator to combine sets.
set_a = {1, 2, 3}
set_b = {3, 4, 5}
# Combine sets
combined_set = set_a | set_b
print(combined_set)
{1, 2, 3, 4, 5}
Sets can be used to track unique users visiting a website or application:
visits = ["user1", "user2", "user1", "user3", "user2"]
unique_visits = set(visits)
print("Unique Users:", unique_visits)
Unique Users: {'user1', 'user2', 'user3'}
Sets can help remove duplicates when you convert a list into a set.
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers)
[1, 2, 3, 4, 5]
Python sets cannot directly include other sets because they are mutable. However, we can use frozenset, which is an immutable version of a set, for this purpose:
inner_set = frozenset({1, 2, 3})
outer_set = {4, 5}
# Adding frozenset
outer_set.add(inner_set)
print(outer_set)
{frozenset({1, 2, 3}), 4, 5}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.