Automatic Duplicate Removal
Concepts covered: Sets
A set does deduplication for free, but the data has to get into the set first. add puts in 1 value, and update puts in every value in an iterable. Neither raises an error when a value is already present. The set stays as it was, and the program moves on.
add: one value, no complaints
visitors = set()
visitors.add("u17")
visitors.add("u42")
visitors.add("u17")
visitors.add("u17")
print(len(visitors))
print("u42" in visitors)Output:
2 True
That was 4 add calls and 2 distinct visitors. The third and fourth calls found "u17" present and did nothing. Compare a list: 4 append calls would store 4 items, and counting distinct visitors would need a loop that checks each new id against everything stored before it.
Inside a loop, add becomes a filter that remembers. The program below walks a list of numbers, offers each even one to a set, and counts what survived.
numbers = [4, 7, 2, 9, 4, 6, 2, 8, 6]
unique_evens = set()
for num in numbers:
if num % 2 == 0:
unique_evens.add(num)
print("Unique even count:", len(unique_evens))
print("Unique evens:", unique_evens)Unique even count: 4
Unique evens: {8, 2, 4, 6}
The 9 numbers include 6 even ones, only 4 of them distinct. The set never needed an if num not in unique_evens check before adding, because add carries that check inside it. The pattern 'add everything, then len' answers 'how many distinct?' with no counters and no nested loop.
log = ["login", "view", "view", "logout", "login", "view"]
actions = set()
for action in log:
actions.add(action)
print(len(actions))
print(len(set(log)) == len(actions))Output:
3 True
The loop and set(log) arrive at the same 3 actions. The loop version is worth its extra lines when you need to do something else per item, such as skip some of them; otherwise set(log) says it shorter.
update: many values at once
update takes an iterable and adds each of its items, one by one, the same way set() does while building. Writing seen.update(items) is the same as a for loop calling seen.add(item) on each item, in 1 line.
seen = {1, 2}
seen.update([2, 3, 4])
print(seen)
seen.update(range(3, 7))
print(seen)
seen.update([])
print(len(seen))Output:
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6}
6The first update offered [2, 3, 4]. 2 was already present, so only 3 and 4 were added. The second offered 3 through 6, and only 5 and 6 changed anything. Updating with an empty list touches nothing. The count ends at 6.
A string is 1 value to add and 4 to update
update walks its argument. A string walks as characters, so tags.update("sale") adds 4 separate members: "s", "a", "l", "e". To add the word as 1 tag, use tags.add("sale") instead; wrapping it in a list, tags.update(["sale"]), also works.
tags = set()
tags.add("sale")
print(len(tags))
tags.update("sale")
print(len(tags))
print("s" in tags, "sale" in tags)Output:
1 5 True True
- add(value)
- Takes exactly 1 value
- Puts that value in as 1 member
- add("sale") adds the word
- add([1, 2]) raises an error: a list can't be a member
- update(iterable)
- Takes something a loop can walk
- Puts each item in as its own member
- update("sale") adds 4 letters
- update([1, 2]) adds 1 and 2
Dedupe and keep arrival order
set(items) removes repeats and forgets which came first. When first appearance matters, a list recording the order and a set answering 'seen before?' work as a pair. The set does the fast check; the list grows only when the check says new.
items = ["apple", "kiwi", "apple", "fig", "kiwi", "plum", "apple"]
seen = set()
unique_ordered = []
for item in items:
if item not in seen:
seen.add(item)
unique_ordered.append(item)
print("Original:", items)
print("Unique, in order:", unique_ordered)Original: ['apple', 'kiwi', 'apple', 'fig', 'kiwi', 'plum', 'apple'] Unique, in order: ['apple', 'kiwi', 'fig', 'plum']
The loop receives 7 items, 4 of them distinct. Each one is tested against seen in 1 step. The list unique_ordered ends as ["apple", "kiwi", "fig", "plum"], first appearances in the order they came, which set(items) alone couldn't promise.
How many members does s hold at the end?
s = {10}
s.add(10)
s.update([10, 20])
s.update("20")
print(len(s))- 4
- 3
- 5
- 2
Lists and sets grow through different method names, and mixing them up is one of the first errors people meet with sets. A list has append because new items go on its end. A set has no end, so it has no append, and calling it stops the program with AttributeError: 'set' object has no attribute 'append'. The reverse holds too: a list has no add.
| Collection | Method that adds 1 value | What a repeat does |
|---|---|---|
| List | `items.append(x)` | Stored again as a new item |
| Set | `items.add(x)` | Changes nothing |
When an error names append on a set, the fix is the method name alone. Everything else, including the final len, stays as written.
About this lesson
This section is part of the Sets: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.