Adding Elements to a Set
To add a new element to a set, use the add()
function.
If the element you are trying to add already exists in the set, the set will not change.
Adding elements to a set
my_set = {1, 2, 3}
print("my_set:", my_set)
# {1, 2, 3}
my_set.add(4)
# Add 4 to my_set
print("add 4:", my_set)
# {1, 2, 3, 4}
# Attempt to add a duplicate element
my_set.add(2)
# Attempt to add 2 to my_set
print("add 2:", my_set)
# {1, 2, 3, 4} (no change)
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.