Python Tutorial
Python Add Set Items
Once a set is created you cannot change items, but you can add new ones with add() or update().
add() and update()
add() takes one item. update() takes any iterable.
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
thisset.update(["mango", "grape"])
print(thisset)📘 Real-World Deep Dive
Growing a set — <code>add</code>, <code>update</code>, <code>|=</code> — is the cheapest way to build a deduplicated collection. Knowing the trade-offs with lists and dicts means picking correctly.
Real-Life Scenario
Roll up log events from several files; keep only unique hostnames (set), keep frequency per hostname (<code>Counter</code>), and emit both.
Real-Life Example
import re
from collections import Counter
HOST_RX = re.compile(r"host=([\w.-]+)")
raw_logs = [
"host=api-1.example.com status=200",
"host=api-2.example.com status=200",
"host=api-1.example.com status=500",
"host=api-1.example.com status=200",
"host=db-1.example.com status=200",
"host=api-2.example.com status=200",
]
hosts: set[str] = set()
freq: Counter[str] = Counter()
for line in raw_logs:
m = HOST_RX.search(line)
if not m:
continue
h = m.group(1)
hosts.add(h) # O(1) amortised
freq[h] += 1
print(f"unique hosts: {len(hosts)}")
for h in sorted(hosts):
print(f" {h:<24} freq={freq[h]}")
print(f"set == dict.keys: {set(freq) == hosts}")Expected Output
unique hosts: 3
api-1.example.com freq=3
api-2.example.com freq=2
db-1.example.com freq=1
set == dict.keys: TrueCommon mistakes
set.add(x)for an existing element is a no-op — don't rely on it for counting.set.update(other)up to 1000× faster than per-element.addin a loop.- Used
setas a list and forgotten the order — usedict.fromkeysfor ordered uniqueness.
🚀 Performance & Best Practices
- Use
set(some_iter)rather than looping over membership-and-add. set.update(other)is C-level; per-element.addin Python is much slower.- Huge unique counts: prefer
hyperloglogfor approximate cardinality.
🧪 Try It Yourself
- Combine set and Counter to print the host with the highest error rate.
- Add a time-window filter using
itertools.groupby. - Build a Bloom-filter fallback for memory-bounded collectors.