ホーム 暮らし The '.add()' method for adding elements to a Python 'set'. What is the definitive difference from 'list.append()'?

The '.add()' method for adding elements to a Python 'set'. What is the definitive difference from 'list.append()'?

三浦 拓海 三浦 拓海 • 更新: • 公開: • 読了約 7 分
目次
nd8aadc559aa3

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.


Use .add() instead of .append() to add 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 biggest 'feature' of .add(): What happens if you add a duplicate element?


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"?

  1. Does it stop with an error (like a ValueError)?

  2. 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.


Read more on the blog: Concrete code for .add() and experiments with '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


同じカテゴリの記事

三浦 拓海
コンテンツディレクター 三浦 拓海
プロフィールを見る →

映画と連続ドラマの公開情報を追う担当。配給会社のプレスシートと公式サイトの発表日を確認したうえで執筆します。

おすすめの関連記事