set.add()

Adds an element to a set. If the element is already there, the set doesn't change.

Returns
None (the set changes in place).
Changes the original
Yes
On this page

Example

#
Python
visited = {"lesson_1", "lesson_2"}

visited.add("lesson_3")
visited.add("lesson_1")

print(len(visited))
print(sorted(visited))
Resultsaved result, you can check it
3
['lesson_1', 'lesson_2', 'lesson_3']

Definition and usage

#

The add(element) method inserts a single element into a set. A set only stores unique values, so adding an element that is already there changes nothing and raises no error.

Set elements must be hashable, meaning immutable in practice: numbers, strings, tuples. Trying to add a list or a dictionary raises a TypeError. Add several elements at once with the update() method.

The method changes the set in place and returns None. Sets have no order, so a new element does not land "at the end" the way it would in a list. For display, it is convenient to sort the set with the sorted() function.

Syntax

#
Syntax
set.add(element)

Parameters

#
  • element

    a hashable value

    The element to add.

More examples

#
Detecting repeats
Python
logins = ["emma", "jack", "emma", "mia", "jack"]
seen = set()
duplicates = set()

for login in logins:
    if login in seen:
        duplicates.add(login)
    seen.add(login)

print(sorted(duplicates))
Resultsaved result, you can check it
['emma', 'jack']
Not every value can be added
Python
tags = set()
tags.add(("python", 3))
print(tags)

try:
    tags.add(["python", 3])
except TypeError:
    print("A list cannot be a set element")
Resultsaved result, you can check it
{('python', 3)}
A list cannot be a set element

Good practices

#
  • A set like seen is great for remembering what you have already encountered. Checking x in seen is fast no matter how many elements there are.
  • Create an empty set only with set(), because {} means an empty dictionary.

Related entries

#

Spotted a mistake or missing an example? Write to us.