Python’s set is a “mutable” (changeable) data type, meaning you can add or remove elements even after creating it. Unlike lists, which use .append(), sets use the .add() method to add elements.
This article explains the basic usage of the .add() method and how it behaves regarding the set’s unique feature of “not allowing duplicates.”
Basic Usage of the .add() Method
The .add() method adds a single element passed as an argument to the set. Since sets do not have the concept of order, the element is not added to a specific position (like the end); it simply becomes part of the set.
Syntax:
set_variable.add(element_to_add)
Example:
# Set of registered users
registered_users = {"tanaka", "sato", "suzuki"}
print(f"Before: {registered_users}")
# Add new user "kato"
registered_users.add("kato")
print(f"After: {registered_users}")
Output:
Before: {'suzuki', 'sato', 'tanaka'}
After: {'kato', 'suzuki', 'sato', 'tanaka'}
(Note: Since sets are unordered, the display order may vary depending on the execution environment.)
Behavior When Adding Duplicate Elements
The biggest characteristic of a set is that it “does not hold duplicate elements.” The .add() method follows this rule. If you try to use .add() to add an element that already exists in the set, no error will occur, but the set will remain unchanged.
Example: Let’s try adding “sato”, which already exists, to the previous set.
registered_users = {'kato', 'suzuki', 'sato', 'tanaka'}
print(f"Before: {registered_users}")
# Add existing user "sato" again
registered_users.add("sato")
print(f"After re-adding: {registered_users}")
Output:
Before: {'kato', 'suzuki', 'sato', 'tanaka'}
After re-adding: {'kato', 'suzuki', 'sato', 'tanaka'}
We added “sato”, but the content of the set is exactly the same before and after. In this way, .add() automatically ignores duplicates.
Summary
- Use the
.add(element)method to add a single element to a set. - If the element you are adding already exists in the set,
.add()does nothing, and no error occurs.
