Join my Asyncio (Python) course on Udemy for free 👀

Use add() to append items to a Set in Python

May 22, 2022  ‐ 1 min read

Even though Sets are quite similar to Lists in Python, there is a differently named method to call when appending items to a set. Instead of the append() method we use add() for sets.

LETTERS = {'p', 'i', 'z'}

LETTERS.add('a')

print(LETTERS)
# => {'i', 'p', 'a', 'z'}

First, Sets are unordered in Python. Therefore the print() function displays the letters in a different order then how the set was created.

Second, in Set theory the items in a set should be unique. Therefore we cannot have the same item twice in a set. This will not show an error, you will just not notice a change to the set.

LETTERS = {'p', 'i', 'z', 'a'}

print(LETTERS)
# => {'i', 'p', 'a', 'z'}

LETTERS.add('z')

print(LETTERS)
# => {'i', 'p', 'a', 'z'}

As you see in the example above, the letter 'z' is only present once after we tried to add a second 'z' to the set.