Collections
Sets
Unique Collections
You're tracking which pages a user has visited. You don't want duplicates, and
you need fast "have they seen this?" checks. Sets automatically ignore duplicates
and provide O(1) membership testing with in.
Collect unique tags
Add items to a set - duplicates are ignored.
def main():
# Create a set of tags for a blog post
tags = set()
print("=== Adding Blog Tags ===")
# Add tags
tags.add("python")
print(f"Added 'python': {tags}")
tags.add("programming")
print(f"Added 'programming': {tags}")
tags.add("tutorial")
print(f"Added 'tutorial': {tags}")
# Try to add duplicate
tags.add("python")
print(f"Added 'python' again: {tags}")
print("Duplicate ignored!")
# Add more tags
tags.add("beginner")
tags.add("coding")
tags.add("python")
print(f"\nWith more tags: {tags}")
print("\n=== Blog Post Tags ===")
print(f"Total unique tags: {len(tags)}")
print(f"Tags: {tags}")
# Display as hashtags
print("\n=== Formatted ===")
hashtags = " ".join(f"#{tag}" for tag in tags)
print(hashtags)
# Alternative creation with literal
print("\n=== Set Literal ===")
colors = {"red", "green", "blue"} # Note: {} is empty dict, not set!
print(f"Colors: {colors}")
main()
main()
43main()44#@help createtags ← set(), hashtags ← #beginner #python #tutorial #programming #coding
1#@var=default,moreTags2def main():3 # Create a set of tags for a blog post #?create4 tags→ set() = set()5 6 print("=== Adding Blog Tags ===")7 8 # Add tags #?add9 tags→ {'python'}.add("python")10 print(f"Added 'python': {tags{'python'}}")11 12 tags→ {'python', 'programming'}.add("programming")13 print(f"Added 'programming': {tags{'python', 'programming'}}")14 15 tags→ {'python', 'tutorial', 'programming'}.add("tutorial")16 print(f"Added 'tutorial': {tags{'python', 'tutorial', 'programming'}}")17 18 # Try to add duplicate #?duplicate19 tags{'python', 'tutorial', 'programming'}.add("python")20 print(f"Added 'python' again: {tags{'python', 'tutorial', 'programming'}}")21 print("Duplicate ignored!")22 23 # Add more tags24 tags→ {'python', 'beginner', 'tutorial', 'programming'}.add("beginner") #@var=_,!25 tags→ {'beginner', 'python', 'tutorial', 'programming', 'coding'}.add("coding") #@var=_,!26 tags{'beginner', 'python', 'tutorial', 'programming', 'coding'}.add("python") #@var=_,! # Still ignored27 print(f"\nWith more tags: {tags{'beginner', 'python', 'tutorial', 'programming', 'coding'}}") #@var=_,!28 29 print("\n=== Blog Post Tags ===")30 print(f"Total unique tags: {len(tags{'beginner', 'python', 'tutorial', 'programming', 'coding'})}")31 print(f"Tags: {tags{'beginner', 'python', 'tutorial', 'programming', 'coding'}}")32 33 # Display as hashtags34 print("\n=== Formatted ===")35 hashtags→ #beginner #python #tutorial #programming #coding = " ".join(f"#{tag}" for tag in tags{'beginner', 'python', 'tutorial', 'programming', 'coding'})36 print(hashtags#beginner #python #tutorial #programming #coding)37 38 # Alternative creation with literal #?literal39 print("\n=== Set Literal ===")40 colors→ {'green', 'red', 'blue'} = {"red", "green", "blue"} # Note: {} is empty dict, not set!41 print(f"Colors: {colors{'green', 'red', 'blue'}}")output=== Adding Blog Tags === Added 'python': {'python'} Added 'programming': {'python', 'programming'} Added 'tutorial': {'python', 'tutorial', 'programming'} Added 'python' again: {'python', 'tutorial', 'programming'} Duplicate ignored! With more tags: {'beginner', 'python', 'tutorial', 'programming', 'coding'} === Blog Post Tags === Total unique tags: 5 Tags: {'beginner', 'python', 'tutorial', 'programming', 'coding'} === Formatted === #beginner #python #tutorial #programming #coding === Set Literal === Colors: {'green', 'red', 'blue'}main()
43main()44#@help create
Use add() to add elements. Duplicates are silently ignored.
Fast membership check
Test if an item is in the set.
def main():
# Create an allowlist of premium users
premium_users = {"alice", "bob", "carol", "david"}
print("=== Premium Membership ===")
print(f"Premium users: {premium_users}")
# Check if user has access
current_user = "bob"
print("\n=== Access Check ===")
print(f"User: {current_user}")
if current_user in premium_users:
print("✓ Premium access granted!")
print("Welcome to exclusive content.")
else:
print("✗ Not a premium user.")
print("Upgrade to access premium features!")
# Blocked users check
blocked_users = {"spammer", "troll", "eve"}
print("\n=== Security Check ===")
if current_user in blocked_users:
print("⛔ User is blocked!")
else:
print("✓ User is not blocked.")
# Check multiple users
print("\n=== Batch Check ===")
users_to_check = ["alice", "eve", "bob", "frank"]
for user in users_to_check:
status = "Premium" if user in premium_users else "Regular"
print(f"{user}: {status}")
# Speed comparison note
print("\n=== Performance Note ===")
print("'in' check for set: O(1) - instant!")
print("'in' check for list: O(n) - slower")
main()
def main():
# Create an allowlist of premium users
premium_users = {"alice", "bob", "carol", "david"}
print("=== Premium Membership ===")
print(f"Premium users: {premium_users}")
# Check if user has access
current_user = "eve"
print("\n=== Access Check ===")
print(f"User: {current_user}")
if current_user in premium_users:
print("✓ Premium access granted!")
print("Welcome to exclusive content.")
else:
print("✗ Not a premium user.")
print("Upgrade to access premium features!")
# Blocked users check
blocked_users = {"spammer", "troll", "eve"}
print("\n=== Security Check ===")
if current_user in blocked_users:
print("⛔ User is blocked!")
else:
print("✓ User is not blocked.")
# Check multiple users
print("\n=== Batch Check ===")
users_to_check = ["alice", "eve", "bob", "frank"]
for user in users_to_check:
status = "Premium" if user in premium_users else "Regular"
print(f"{user}: {status}")
# Speed comparison note
print("\n=== Performance Note ===")
print("'in' check for set: O(1) - instant!")
print("'in' check for list: O(n) - slower")
main()
main()
44main()45#@help allowlistpremium_users ← {'carol', 'alice', 'bob', 'david'}, current_user ← bob
1#@var=default,blocked2def main():3 # Create an allowlist of premium users #?allowlist4 premium_users→ {'carol', 'alice', 'bob', 'david'} = {"alice", "bob", "carol", "david"}5 6 print("=== Premium Membership ===")7 print(f"Premium users: {premium_users{'carol', 'alice', 'bob', 'david'}}")8 9 # Check if user has access #?in10 current_user→ bob = "bob" #@var=_,eve11 12 print("\n=== Access Check ===")13 print(f"User: {current_userbob}")output=== Premium Membership === Premium users: {'carol', 'alice', 'bob', 'david'} === Access Check === User: bobif current_user in premium_users:
15if current_userbob in premium_users{'carol', 'alice', 'bob', 'david'}:16 print("✓ Premium access granted!")17 print("Welcome to exclusive content.")18else:output✓ Premium access granted! Welcome to exclusive content.blocked_users ← {'troll', 'spammer', 'eve'}
22# Blocked users check #@var=!,_23blocked_users→ {'troll', 'spammer', 'eve'} = {"spammer", "troll", "eve"}2425print("\n=== Security Check ===") #@var=!,_26if current_user in blocked_users: #@var=!,_output === Security Check ===#@var=!,_ else: #@var=!,_
26if current_user in blocked_users: #@var=!,_27 print("⛔ User is blocked!") #@var=!,_28else: #@var=!,_29 print("✓ User is not blocked.") #@var=!,_output✓ User is not blocked.users_to_check ← ['alice', 'eve', 'bob', 'frank']
31# Check multiple users32print("\n=== Batch Check ===")33users_to_check→ ['alice', 'eve', 'bob', 'frank'] = ["alice", "eve", "bob", "frank"]output === Batch Check ===status ← Premium
pass 1 of 435for useralice in users_to_check['alice', 'eve', 'bob', 'frank']:36 status→ Premium = "Premium" if useralice in premium_users{'carol', 'alice', 'bob', 'david'} else "Regular"37 print(f"{useralice}: {statusPremium}")outputalice: PremiumAll 4 passes — pass 1 is the card above pass userstatus1 alice Premium 2 eve Regular 3 bob Premium 4 frank Regular print(" === Performance Note ===")
39# Speed comparison note #?speed40print("\n=== Performance Note ===")41print("'in' check for set: O(1) - instant!")42print("'in' check for list: O(n) - slower")output === Performance Note === 'in' check for set: O(1) - instant! 'in' check for list: O(n) - slowermain()
44main()45#@help allowlist
main()
43main()premium_users ← {'david', 'bob', 'alice', 'carol'}, current_user ← eve
1def main():2 # Create an allowlist of premium users3 premium_users→ {'david', 'bob', 'alice', 'carol'} = {"alice", "bob", "carol", "david"}4 5 print("=== Premium Membership ===")6 print(f"Premium users: {premium_users{'david', 'bob', 'alice', 'carol'}}")7 8 # Check if user has access9 current_user→ eve = "eve"10 11 print("\n=== Access Check ===")12 print(f"User: {current_usereve}")output=== Premium Membership === Premium users: {'david', 'bob', 'alice', 'carol'} === Access Check === User: eveelse:
15 print("✓ Premium access granted!")16 print("Welcome to exclusive content.")17else:18 print("✗ Not a premium user.")19 print("Upgrade to access premium features!")output✗ Not a premium user. Upgrade to access premium features!blocked_users ← {'troll', 'eve', 'spammer'}
21# Blocked users check22blocked_users→ {'troll', 'eve', 'spammer'} = {"spammer", "troll", "eve"}2324print("\n=== Security Check ===")25if current_user in blocked_users:output === Security Check ===if current_user in blocked_users:
24print("\n=== Security Check ===")25if current_usereve in blocked_users{'troll', 'eve', 'spammer'}:26 print("⛔ User is blocked!")27else:output⛔ User is blocked!users_to_check ← ['alice', 'eve', 'bob', 'frank']
30# Check multiple users31print("\n=== Batch Check ===")32users_to_check→ ['alice', 'eve', 'bob', 'frank'] = ["alice", "eve", "bob", "frank"]output === Batch Check ===status ← Premium
pass 1 of 434for useralice in users_to_check['alice', 'eve', 'bob', 'frank']:35 status→ Premium = "Premium" if useralice in premium_users{'david', 'bob', 'alice', 'carol'} else "Regular"36 print(f"{useralice}: {statusPremium}")outputalice: PremiumAll 4 passes — pass 1 is the card above pass userstatus1 alice Premium 2 eve Regular 3 bob Premium 4 frank Regular print(" === Performance Note ===")
38# Speed comparison note39print("\n=== Performance Note ===")40print("'in' check for set: O(1) - instant!")41print("'in' check for list: O(n) - slower")output === Performance Note === 'in' check for set: O(1) - instant! 'in' check for list: O(n) - slowermain()
43main()
item in s is O(1) - much faster than list's O(n) search.
Remove an item
Remove elements with remove() or discard().
def main():
cart = {"Laptop", "Mouse", "Keyboard", "Monitor", "Headphones"}
print("=== Shopping Cart ===")
print(f"Items: {cart}")
print(f"Count: {len(cart)}")
# remove() vs discard()
print("\n=== Removing Items ===")
# remove() raises KeyError if not found
to_remove = "Mouse"
cart.remove(to_remove)
print(f"Removed '{to_remove}': {cart}")
# discard() does nothing if not found (no error!)
not_in_cart = "Tablet"
cart.discard(not_in_cart)
print(f"Discard '{not_in_cart}' (not in cart): no error!")
print(f"Cart unchanged: {cart}")
# This would cause error:
# cart.remove("Tablet") # KeyError!
# Remove more items
cart.discard("Keyboard")
cart.discard("Monitor")
print(f"\nAfter more removals: {cart}")
# Clear all
print("\n=== Clearing Cart ===")
print(f"Before clear: {len(cart)} items")
cart.clear()
print(f"After clear: {len(cart)} items")
print(f"Cart is empty: {len(cart) == 0}")
# pop() - remove arbitrary item
demo_set = {1, 2, 3, 4, 5}
print("\n=== pop() Demo ===")
print(f"Set: {demo_set}")
popped = demo_set.pop() # Removes and returns ONE item
print(f"Popped: {popped}")
print(f"Remaining: {demo_set}")
main()
main()
46main()47#@help removecart ← {'Mouse', 'Headphones', 'Monitor', 'Laptop', 'Keyboard'}
1#@var=default,clearAll2def main():3 cart→ {'Mouse', 'Headphones', 'Monitor', 'Laptop', 'Keyboard'} = {"Laptop", "Mouse", "Keyboard", "Monitor", "Headphones"}4 5 print("=== Shopping Cart ===")6 print(f"Items: {cart{'Mouse', 'Headphones', 'Monitor', 'Laptop', 'Keyboard'}}")7 print(f"Count: {len(cart{'Mouse', 'Headphones', 'Monitor', 'Laptop', 'Keyboard'})}")8 9 # remove() vs discard() #?remove10 print("\n=== Removing Items ===")11 12 # remove() raises KeyError if not found13 to_remove→ Mouse = "Mouse"14 cart→ {'Headphones', 'Monitor', 'Laptop', 'Keyboard'}.remove(to_removeMouse)15 print(f"Removed '{to_removeMouse}': {cart{'Headphones', 'Monitor', 'Laptop', 'Keyboard'}}")16 17 # discard() does nothing if not found (no error!) #?discard18 not_in_cart→ Tablet = "Tablet"19 cart{'Headphones', 'Monitor', 'Laptop', 'Keyboard'}.discard(not_in_cartTablet)20 print(f"Discard '{not_in_cartTablet}' (not in cart): no error!")21 print(f"Cart unchanged: {cart{'Headphones', 'Monitor', 'Laptop', 'Keyboard'}}")22 23 # This would cause error:24 # cart.remove("Tablet") # KeyError!25 26 # Remove more items27 cart→ {'Headphones', 'Monitor', 'Laptop'}.discard("Keyboard") #@var=_,!28 cart→ {'Headphones', 'Laptop'}.discard("Monitor") #@var=_,!29 print(f"\nAfter more removals: {cart{'Headphones', 'Laptop'}}") #@var=_,!30 31 # Clear all #?clear #@var=!,_32 print("\n=== Clearing Cart ===") #@var=!,_33 print(f"Before clear: {len(cart{'Headphones', 'Laptop'})} items") #@var=!,_34 cart→ set().clear() #@var=!,_35 print(f"After clear: {len(cartset())} items") #@var=!,_36 print(f"Cart is empty: {len(cartset()) == 0}") #@var=!,_37 38 # pop() - remove arbitrary item #?pop39 demo_set→ {1, 2, 3, 4, 5} = {1, 2, 3, 4, 5}40 print("\n=== pop() Demo ===")41 print(f"Set: {demo_set{1, 2, 3, 4, 5}}")42 popped→ 1 = demo_set→ {2, 3, 4, 5}.pop() # Removes and returns ONE item43 print(f"Popped: {popped1}")44 print(f"Remaining: {demo_set{2, 3, 4, 5}}")output=== Shopping Cart === Items: {'Mouse', 'Headphones', 'Monitor', 'Laptop', 'Keyboard'} Count: 5 === Removing Items === Removed 'Mouse': {'Headphones', 'Monitor', 'Laptop', 'Keyboard'} Discard 'Tablet' (not in cart): no error! Cart unchanged: {'Headphones', 'Monitor', 'Laptop', 'Keyboard'} After more removals: {'Headphones', 'Laptop'} === Clearing Cart === Before clear: 2 items After clear: 0 items Cart is empty: True === pop() Demo === Set: {1, 2, 3, 4, 5} Popped: 1 Remaining: {2, 3, 4, 5}main()
46main()47#@help remove
remove() raises KeyError if missing. discard() doesn't.
Combine two sets
Create a union of two sets.
def main():
# Two teams' skill sets
team_a = {"Java", "Python", "SQL", "Git"}
team_b = {"JavaScript", "Python", "CSS", "Git"}
print("=== Team Skills ===")
print(f"Team A: {team_a}")
print(f"Team B: {team_b}")
# Union: All skills combined
all_skills = team_a | team_b # Or: team_a.union(team_b)
print("\n=== Union (All Skills) ===")
print(f"Combined: {all_skills}")
print("(Duplicates automatically removed)")
# Alternative syntax
all_skills_method = team_a.union(team_b)
print(f"Using .union(): {all_skills_method}")
# Count unique skills
print("\n=== Statistics ===")
print(f"Team A skills: {len(team_a)}")
print(f"Team B skills: {len(team_b)}")
print(f"Unique combined: {len(all_skills)}")
overlap = len(team_a) + len(team_b) - len(all_skills)
print(f"Overlap count: {overlap}")
# Practical example: Merge user permissions
print("\n=== Permission Merge ===")
basic_perms = {"read", "comment"}
editor_perms = {"read", "write", "edit", "comment"}
admin_perms = {"read", "write", "edit", "delete", "manage"}
# Build editor permissions (basic + editor)
full_editor_perms = basic_perms | editor_perms
print(f"Editor has: {full_editor_perms}")
# Build admin permissions (all combined)
full_admin_perms = basic_perms | editor_perms | admin_perms
print(f"Admin has: {full_admin_perms}")
# Update in place with |=
user_perms = {"read"}
user_perms |= {"comment", "vote"} # Add more
print(f"\nUser perms after |=: {user_perms}")
main()
main()
49main()50#@help unionteam_a ← {'Python', 'Java', 'Git', 'SQL'}, team_b ← {'JavaScript', 'CSS', 'Python', 'Git'}
1def main():2 # Two teams' skill sets3 team_a→ {'Python', 'Java', 'Git', 'SQL'} = {"Java", "Python", "SQL", "Git"}4 team_b→ {'JavaScript', 'CSS', 'Python', 'Git'} = {"JavaScript", "Python", "CSS", "Git"}5 6 print("=== Team Skills ===")7 print(f"Team A: {team_a{'Python', 'Java', 'Git', 'SQL'}}")8 print(f"Team B: {team_b{'JavaScript', 'CSS', 'Python', 'Git'}}")9 10 # Union: All skills combined #?union11 all_skills→ {'SQL', 'CSS', 'Java', 'Python', 'JavaScript', 'Git'} = team_a{'Python', 'Java', 'Git', 'SQL'} | team_b{'JavaScript', 'CSS', 'Python', 'Git'} # Or: team_a.union(team_b)12 13 print("\n=== Union (All Skills) ===")14 print(f"Combined: {all_skills{'SQL', 'CSS', 'Java', 'Python', 'JavaScript', 'Git'}}")15 print("(Duplicates automatically removed)")16 17 # Alternative syntax18 all_skills_method→ {'SQL', 'CSS', 'Java', 'Python', 'JavaScript', 'Git'} = team_a{'Python', 'Java', 'Git', 'SQL'}.union(team_b{'JavaScript', 'CSS', 'Python', 'Git'})19 print(f"Using .union(): {all_skills_method{'SQL', 'CSS', 'Java', 'Python', 'JavaScript', 'Git'}}")20 21 # Count unique skills22 print("\n=== Statistics ===")23 print(f"Team A skills: {len(team_a{'Python', 'Java', 'Git', 'SQL'})}")24 print(f"Team B skills: {len(team_b{'JavaScript', 'CSS', 'Python', 'Git'})}")25 print(f"Unique combined: {len(all_skills{'SQL', 'CSS', 'Java', 'Python', 'JavaScript', 'Git'})}")26 overlap→ 2 = len(team_a{'Python', 'Java', 'Git', 'SQL'}) + len(team_b{'JavaScript', 'CSS', 'Python', 'Git'}) - len(all_skills{'SQL', 'CSS', 'Java', 'Python', 'JavaScript', 'Git'})27 print(f"Overlap count: {overlap2}")28 29 # Practical example: Merge user permissions #?perms30 print("\n=== Permission Merge ===")31 32 basic_perms→ {'comment', 'read'} = {"read", "comment"}33 editor_perms→ {'write', 'edit', 'comment', 'read'} = {"read", "write", "edit", "comment"}34 admin_perms→ {'edit', 'write', 'delete', 'manage', 'read'} = {"read", "write", "edit", "delete", "manage"}35 36 # Build editor permissions (basic + editor)37 full_editor_perms→ {'edit', 'comment', 'write', 'read'} = basic_perms{'comment', 'read'} | editor_perms{'write', 'edit', 'comment', 'read'}38 print(f"Editor has: {full_editor_perms{'edit', 'comment', 'write', 'read'}}")39 40 # Build admin permissions (all combined)41 full_admin_perms→ {'comment', 'write', 'delete', 'manage', 'read', 'edit'} = basic_perms{'comment', 'read'} | editor_perms{'write', 'edit', 'comment', 'read'} | admin_perms{'edit', 'write', 'delete', 'manage', 'read'}42 print(f"Admin has: {full_admin_perms{'comment', 'write', 'delete', 'manage', 'read', 'edit'}}")43 44 # Update in place with |= #?inplace45 user_perms→ {'read'} = {"read"}46 user_perms→ {'vote', 'comment', 'read'} |= {"comment", "vote"} # Add more47 print(f"\nUser perms after |=: {user_perms{'vote', 'comment', 'read'}}")output=== Team Skills === Team A: {'Python', 'Java', 'Git', 'SQL'} Team B: {'JavaScript', 'CSS', 'Python', 'Git'} === Union (All Skills) === Combined: {'SQL', 'CSS', 'Java', 'Python', 'JavaScript', 'Git'} (Duplicates automatically removed) Using .union(): {'SQL', 'CSS', 'Java', 'Python', 'JavaScript', 'Git'} === Statistics === Team A skills: 4 Team B skills: 4 Unique combined: 6 Overlap count: 2 === Permission Merge === Editor has: {'edit', 'comment', 'write', 'read'} Admin has: {'comment', 'write', 'delete', 'manage', 'read', 'edit'} User perms after |=: {'vote', 'comment', 'read'}main()
49main()50#@help union
Use | operator or union() method. Result has all unique elements.
Remove duplicates from list
Convert a list to set to eliminate duplicates.
def main():
# List with duplicate entries
emails = [
"alice@example.com",
"bob@example.com",
"alice@example.com", # duplicate
"carol@example.com",
"bob@example.com", # duplicate
"david@example.com",
"alice@example.com" # duplicate
]
print("=== Email List (with duplicates) ===")
print(f"Emails: {emails}")
print(f"Count: {len(emails)}")
# Remove duplicates using set
unique_emails = set(emails)
print("\n=== After Removing Duplicates ===")
print(f"Unique: {unique_emails}")
print(f"Count: {len(unique_emails)}")
print(f"Removed {len(emails) - len(unique_emails)} duplicates")
# Convert back to list if needed
cleaned_list = list(unique_emails)
print(f"\nAs list: {cleaned_list}")
# PRESERVE ORDER: use dict.fromkeys()
print("\n=== Preserving Order ===")
ordered_unique = list(dict.fromkeys(emails))
print(f"Order preserved: {ordered_unique}")
print("(dict maintains insertion order in Python 3.7+)")
# One-liner pattern
print("\n=== One-liner Dedup ===")
nums = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
unique_nums = list(set(nums))
print(f"Original: {nums}")
print(f"Unique (order lost): {unique_nums}")
# Duplicate analysis
print("\n=== Duplicate Analysis ===")
from collections import Counter
counts = Counter(emails)
for email, count in counts.items():
if count > 1:
print(f"{email} appeared {count} times")
main()
main()
52main()53#@help dedupemails ← ['alice@example.com', 'bob@example.com', 'alice@example.com', 'carol@example.com', 'bob@example.com', 'david@example.com', 'alice@example.com']
1#@var=default,preserveOrder2def main():3 # List with duplicate entries4 emails→ ['alice@example.com', 'bob@example.com', 'alice@example.com', 'carol@example.com', 'bob@example.com', 'david@example.com', 'alice@example.com'] = [5 "alice@example.com",6 "bob@example.com",7 "alice@example.com", # duplicate8 "carol@example.com",9 "bob@example.com", # duplicate10 "david@example.com",11 "alice@example.com" # duplicate12 ]13 14 print("=== Email List (with duplicates) ===")15 print(f"Emails: {emails['alice@example.com', 'bob@example.com', 'alice@example.com', 'carol@example.com', 'bob@example.com', 'david@example.com', 'alice@example.com']}")16 print(f"Count: {len(emails['alice@example.com', 'bob@example.com', 'alice@example.com', 'carol@example.com', 'bob@example.com', 'david@example.com', 'alice@example.com'])}")17 18 # Remove duplicates using set #?dedup19 unique_emails→ {'alice@example.com', 'bob@example.com', 'carol@example.com', 'david@example.com'} = set(emails['alice@example.com', 'bob@example.com', 'alice@example.com', 'carol@example.com', 'bob@example.com', 'david@example.com', 'alice@example.com'])20 21 print("\n=== After Removing Duplicates ===")22 print(f"Unique: {unique_emails{'alice@example.com', 'bob@example.com', 'carol@example.com', 'david@example.com'}}")23 print(f"Count: {len(unique_emails{'alice@example.com', 'bob@example.com', 'carol@example.com', 'david@example.com'})}")24 print(f"Removed {len(emails['alice@example.com', 'bob@example.com', 'alice@example.com', 'carol@example.com', 'bob@example.com', 'david@example.com', 'alice@example.com']) - len(unique_emails{'alice@example.com', 'bob@example.com', 'carol@example.com', 'david@example.com'})} duplicates")25 26 # Convert back to list if needed #?convert27 cleaned_list→ ['alice@example.com', 'bob@example.com', 'carol@example.com', 'david@example.com'] = list(unique_emails{'alice@example.com', 'bob@example.com', 'carol@example.com', 'david@example.com'})28 print(f"\nAs list: {cleaned_list['alice@example.com', 'bob@example.com', 'carol@example.com', 'david@example.com']}")29 30 # PRESERVE ORDER: use dict.fromkeys() #?order #@var=!,_31 print("\n=== Preserving Order ===")32 ordered_unique→ ['alice@example.com', 'bob@example.com', 'carol@example.com', 'david@example.com'] = list(dict.fromkeys(emails['alice@example.com', 'bob@example.com', 'alice@example.com', 'carol@example.com', 'bob@example.com', 'david@example.com', 'alice@example.com']))33 print(f"Order preserved: {ordered_unique['alice@example.com', 'bob@example.com', 'carol@example.com', 'david@example.com']}")34 print("(dict maintains insertion order in Python 3.7+)")35 36 # One-liner pattern37 print("\n=== One-liner Dedup ===")38 nums→ [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]39 unique_nums→ [1, 2, 3, 4, 5, 6, 9] = list(set(nums[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]))40 print(f"Original: {nums[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]}")41 print(f"Unique (order lost): {unique_nums[1, 2, 3, 4, 5, 6, 9]}")42 43 # Duplicate analysis #?analysis44 print("\n=== Duplicate Analysis ===")45 from collections import Counter46 counts→ Counter({'alice@example.com': 3, 'bob@example.com': 2, 'carol@example.com': 1, 'david@example.com': 1}) = Counter(emails['alice@example.com', 'bob@example.com', 'alice@example.com', 'carol@example.com', 'bob@example.com', 'david@example.com', 'alice@example.com'])output=== Email List (with duplicates) === Emails: ['alice@example.com', 'bob@example.com', 'alice@example.com', 'carol@example.com', 'bob@example.com', 'david@example.com', 'alice@example.com'] Count: 7 === After Removing Duplicates === Unique: {'alice@example.com', 'bob@example.com', 'carol@example.com', 'david@example.com'} Count: 4 Removed 3 duplicates As list: ['alice@example.com', 'bob@example.com', 'carol@example.com', 'david@example.com'] === Preserving Order === Order preserved: ['alice@example.com', 'bob@example.com', 'carol@example.com', 'david@example.com'] (dict maintains insertion order in Python 3.7+) === One-liner Dedup === Original: [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] Unique (order lost): [1, 2, 3, 4, 5, 6, 9] === Duplicate Analysis ===for email, count in counts.items():
pass 1 of 448for emailalice@example.com, count3 in countsCounter({'alice@example.com': 3, 'bob@example.com': 2, 'carol@example.com': 1, 'david@example.com': 1}).items():49 if count > 1:50 print(f"{email} appeared {count} times")All 4 passes — pass 1 is the card above pass emailcount1 alice@example.com 3 2 bob@example.com 2 3 carol@example.com 1 4 david@example.com 1 if count > 1:
pass 1 of 248for email, count in counts.items():49 if count3 > 1:50 print(f"{emailalice@example.com} appeared {count3} times")outputalice@example.com appeared 3 timesif count > 1:
pass 2 of 248for email, count in counts.items():49 if count2 > 1:50 print(f"{emailbob@example.com} appeared {count2} times")outputbob@example.com appeared 2 timesmain()
52main()53#@help dedup
set(list) creates a set, automatically removing duplicates.
Exercise: set_operations.py
Explore intersection, difference, and symmetric difference