How to Add to a Set in Python

What you’ll build or solve

You’ll add one item or many items to a set without duplicating values or adding the wrong thing.

When this approach works best

Adding to a set works best when you want to:

  • Keep a collection of tags, IDs, or keywords with no duplicates.
  • Track “seen” items while processing data, like usernames you already handled.
  • Combine values from multiple sources, like merging allowed roles from two configs.

A set is a bad fit when order matters or when you need duplicates. In those cases, use a list.

Prerequisites

  • Python installed
  • You know what a variable and a loop are

Step-by-step instructions

1) Add a single item with add()

Use set.add(value) to add one element.

seen=set()

seen.add("mina")
seen.add("ivan")
seen.add("mina")# duplicate, set stays the same

print(seen)

What to look for: add() ignores duplicates, and it returns None, so don’t assign its result to a variable.


2) Add multiple items with update()

Use set.update(iterable) when you have many values to add.

skills= {"python","sql"}
new_skills= ["api","regex","python"]# python already exists

skills.update(new_skills)
print(skills)

Option A (most common): add from a list, tuple, or another set

a= {1,2}
b= {2,3,4}

a.update(b)
print(a)# {1, 2, 3, 4}

Option B (merge in-place): use |=

a= {1,2}
a|= {2,3}
print(a)

What to look for: update() loops over its input. If you pass a string, it adds characters, not the whole string.


Examples you can copy

Example 1: Track unique visitors

visits= ["u1","u2","u1","u3","u2"]

unique_visitors=set()
foruser_idinvisits:
unique_visitors.add(user_id)

print(len(unique_visitors))
print(unique_visitors)

Example 2: Merge allowlists from two configs

config_a= {"read","write"}
config_b= {"read","admin"}

allowed=set()
allowed.update(config_a)
allowed.update(config_b)

print(allowed)

Example 3: Add unique file extensions from filenames

files= ["report.pdf","photo.jpg","archive.tar.gz","README"]

exts=set()
fornameinfiles:
if"."inname:
exts.add(name.rsplit(".",1)[1].lower())

print(exts)

Example 4: Add tuples when you need pairs

Tuples work in sets, so you can store pairs like coordinates.

points=set()
points.add((10,5))
points.add((10,5))# duplicate tuple
points.add((2,8))

print(points)

Example 5: Build a set in one line (when no conditions needed)

names= ["Naomi","ivan","LEA","Naomi"]
unique_lower= {n.lower()forninnames}
print(unique_lower)

Example 6: Build a set while cleaning input data

raw_tags= ["python","  Python  ","sql","SQL","api"]
tags=set()

fortinraw_tags:
cleaned=t.strip().lower()
ifcleaned:
tags.add(cleaned)

print(tags)

Common mistakes and how to fix them

Mistake 1: Using update() with a string

What you might do

tags= {"python"}
tags.update("api")
print(tags)# adds 'a', 'p', 'i'

Why it breaks

update() expects an iterable of items, and a string is an iterable of characters.

Fix

Use add() for a single string, or wrap it in a list.

tags= {"python"}
tags.add("api")
print(tags)

tags.update(["regex","sql"])
print(tags)

Mistake 2: Adding an unhashable type (like a list or dict)

What you might do

s=set()
s.add([1,2,3])

Why it breaks

Lists and dicts can change, so Python won’t let them be set elements.

Fix

Use a tuple, or convert to a stable representation.

s=set()
s.add((1,2,3))# tuple is hashable
print(s)

Mistake 3: Expecting add() to return the updated set

What you might do

s= {1,2}
s=s.add(3)# s becomes None
print(s)

Why it breaks

add() modifies the set in place and returns None.

Fix

Call add() without assigning.

s= {1,2}
s.add(3)
print(s)

Troubleshooting

If you see TypeError: unhashable type: 'list', convert the value to a tuple, or store a string ID instead of the whole object.

If your set contains single letters after adding a word, you probably used update() with a string. Switch to add("word").

If you get AttributeError: 'dict' object has no attribute 'add', you created {} which is a dict. Create an empty set with set().

If items “disappear,” remember that sets remove duplicates by design. Print the set after each add() to confirm what values are actually different.


Quick recap

  • Use add() to add one item.
  • Use update() (or |=) to add many items.
  • Don’t use update() with a string unless you want characters.
  • Sets only accept hashable values like strings, numbers, and tuples.
  • add() returns None, so don’t assign its result to a variable.