intermediatePython Framework • Core Concepts

Sets: Unique Collections

Join 1.2k+ learners

Introduction to Sets

A set is an unordered collection of unique elements. It doesn't allow duplicates. Unlike lists, sets don't record element position or order of insertion.

Python
# Duplicates are automatically removed numbers = {1, 2, 2, 3, 3, 3} print(numbers) # Output: {1, 2, 3}

Creating Sets

Use curly braces {} for non-empty sets, or the set() constructor with a list/tuple. Note: {} creates an empty DICTIONARY, so use set() for empty sets.

Python
# Literal syntax fruits = {"apple", "banana"} # Constructor (from list) colors = set(["red", "blue", "red"]) # Empty set (Important!) empty_set = set() empty_dict = {} # This is a dict

Basic Operations: Add & Remove

Sets are mutable. Use .add() to insert elements. Use .remove() (raises error if missing) or .discard() (no error if missing) to delete them. .clear() empties the set.

Python
s = {1, 2, 3} # Add s.add(4) # Remove s.remove(2) s.discard(99) # No error despite 99 missing # Clear s.clear()

Membership Testing

Checking if an item exists in a set using the 'in' keyword is extremely fast (O(1) complexity), much faster than finding an item in a list.

Python
blocked_users = {"spam_bot", "hacker_123"} user = "alice" if user in blocked_users: print("Access Denied") else: print("Welcome!")

Set Operations: Union & Intersection

Combine sets or find commonalities. Union (|) allows all unique items from both. Intersection (&) keeps only items found in BOTH sets.

Python
a = {1, 2, 3} b = {3, 4, 5} print(a | b) # Union: {1, 2, 3, 4, 5} print(a & b) # Intersection: {3}

Difference & Symmetric Difference

Difference (-) removes items belonging to the second set. Symmetric Difference (^) keeps items that are unique to EITHER set (removes the intersection).

Python
a = {1, 2, 3} b = {3, 4, 5} # Difference (in a, NOT in b) print(a - b) # {1, 2} # Symmetric Difference (unique to each) print(a ^ b) # {1, 2, 4, 5}

Iteration

You can loop through a set, but remember the order is not guaranteed.

Python
colors = {"red", "green", "blue"} for color in colors: print(color) # Could print: red, blue, green (random order)

Frozen Sets

A 'frozenset' is an immutable version of a set. Once created, you cannot add or remove items. It can be used as a dictionary key or an element in another set.

Python
# Immutable set fs = frozenset([1, 2, 3]) # fs.add(4) # ERROR! # Using as dict key (valid since it's hashable) locations = { frozenset([0, 0]): "Home" }

Real-World Examples

Sets are perfect for deduplication (removing duplicates from a list) and tracking unique events/visitors.

Python
# Deduplicate a list raw_data = ["apple", "banana", "apple", "orange"] unique_fruits = list(set(raw_data)) print(unique_fruits) # ['apple', 'banana', 'orange']

Master this concept

Hands-on practice is the fastest way to learn. Head over to our interactive workspace to solve this topic's challenge.

Launch Editor