Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
DATA STRUCTURES Module 3 - Data Structures Python Python Basics Python Programming: From Zero to Real-World Applications

Sets - Unique Collections in Python

Reviewed & accurate
AI Summary

What You Will Learn

Beginner

  • What sets are and when to use them
  • Set operations (union, intersection, difference)
  • Removing duplicates
Terminalpython
# Creating sets
fruits = {"apple", "banana", "cherry"}
numbers = set([1, 2, 2, 3, 3, 3])  # {1, 2, 3} - removes duplicates!

# Add and remove
fruits.add("date")
fruits.remove("banana")    # Raises KeyError if not found
fruits.discard("grape")    # Safe removal (no error if missing)

# Check membership (very fast!)
print("apple" in fruits)    # True

# Length (count of unique items)
print(len(fruits))

Set Operations

Terminalpython
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

# Union (all unique items)
print(a | b)        # {1, 2, 3, 4, 5, 6}
print(a.union(b))   # same

# Intersection (common items)
print(a & b)                 # {3, 4}
print(a.intersection(b))     # same

# Difference (in a but not in b)
print(a - b)             # {1, 2}
print(a.difference(b))   # same

# Symmetric difference (in one, not both)
print(a ^ b)     # {1, 2, 5, 6}
Remove duplicates from a list
list(set(my_list)) - the fastest way to remove duplicates. But order is lost. Use dict.fromkeys() to preserve order.

Practical Exercise

Create a set from [1, 1, 2, 2, 3, 3] - duplicates removed!
Union: {1,2,3} | {3,4,5}
Intersection: {1,2,3} & {2,3,4}
Difference: {1,2,3} - {2,3,4}

Key Takeaways

  • Sets store unique items only - no duplicates.
  • Create from list: set([1,1,2]) = {1,2}.
  • Operations: | (union), & (intersection), - (difference), ^ (symmetric).
  • discard() removes safely (no KeyError).
  • in check is O(1) - very fast for large collections.
Previously: Lesson 20 covered dict methods.
Today: You learned: Sets - for unique items and set operations.
Next: Lesson 22 covers string formatting.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments