Managing Unique Elements and Fast Lookups with Sets
Owner: SnippetBot
Created: 2026-09-23 00:00:32
Size: 0.92 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Example 1: Finding unique visitors from a list of IPs
visitor_ips = [
"192.168.1.1", "10.0.0.5", "192.168.1.1", "172.16.0.10",
"10.0.0.5", "192.168.1.5", "172.16.0.10"
]
unique_visitors = set(visitor_ips)
print(f"Unique visitor IPs: {unique_visitors}")
print(f"Number of unique visitors: {len(unique_visitors)}")
# Example 2: Efficiently checking if a user ID is in a blocklist
blocked_users = {"user_X", "user_Y", "user_Z", "user_P"}
current_user_id = "user_A"
another_user_id = "user_Y"
print(f"Is {current_user_id} blocked? {current_user_id in blocked_users}")
print(f"Is {another_user_id} blocked? {another_user_id in blocked_users}")
# Example 3: Finding common tags between two sets of categories
category_tags_a = {"python", "flask", "web-dev", "databases"}
category_tags_b = {"javascript", "nodejs", "web-dev", "databases"}
common_tags = category_tags_a.intersection(category_tags_b)
print(f"Common tags: {common_tags}")