When handling multiple pieces of data together in Python, along with 'list', another useful type is set. A set has a very powerful feature: it does not contain duplicate elements.
Like a list, a set is also a mutable data type. In other words, even after creating it with set() or , you can freely add or remove elements.
If you are used to working with lists, you might be tempted to use the .append() method when adding elements to a set. However, the correct method for adding a single element to a set is .add().
my_set.add("new_element")
Unlike a list, a set does not have the concept of 'order', so an element added with .add() is not added to the 'end', but simply 'added as a member of the set'.
The golden rule of a set is that it does not allow duplicates. So, what happens if you try to .add("sato") again to a set that already contains "sato", "suzuki"?
Does it stop with an error (like a ValueError)?
Is "sato" added as a second element?
The answer to both is 'No'.
A set always adheres to its 'no duplicates' rule. Even if you try to add an existing element with .add(), the set remains unchanged and no error occurs. It is simply quietly ignored.
This behavior is a major advantage of sets, as it allows you to perform 'add' operations safely without worrying about duplicates.
In this article, we introduced the 'concept' of .add() for adding elements to a set, and the 'behavior' when adding duplicate values.
You might be thinking, "So, what is the specific Python code for adding a new element to a set?" or "If I try to add an element that already exists (a duplicate) to a set, I want to check with a 'before and after' print() to see if the list really doesn't change."
Some of you may have felt this way.
On the technical blog I run, as a continuation of this article, I explain in detail with specific Python sample code, from the basic usage of the .add() method to the execution results when adding duplicate elements.
To understand the 'deduplication' nature of sets through code, please check the details via the link below.
▼ Click here for the blog post Adding elements to a Python set: How to use the .add() method