Skip to content

Core Data Structures in Python: list, tuple, dict, set

  • The four core collection types and how they differ on ordering, mutability, and uniqueness.
  • Common operations and performance characteristics for each type.
  • How to pick the right type for a given problem.
  • Realistic examples using an OrdersPortal inventory and order system.

Python provides four built-in collection types that cover the vast majority of data-grouping needs: list, tuple, dict, and set. Each makes different trade-offs between ordering, mutability, and uniqueness. Choosing the right type upfront makes code clearer and avoids subtle bugs.

Save all examples as a .py file and run with python examples.py (Python 3.9+).

list — ordered, mutable, allows duplicates

Section titled “list — ordered, mutable, allows duplicates”

A list is an ordered sequence of objects. You can change it after creation: add, remove, or update elements. Lists preserve insertion order and allow duplicate values.

# OrdersPortal: a queue of pending order IDs
pending_orders = ["ORD-001", "ORD-002", "ORD-003"]
# Access by index (0-based)
print(pending_orders[0]) # ORD-001
print(pending_orders[-1]) # ORD-003 (last element)
# Add to the end
pending_orders.append("ORD-004")
# Insert at a position
pending_orders.insert(1, "ORD-001B")
# Remove by value
pending_orders.remove("ORD-001B")
# Remove by index and return the value
last = pending_orders.pop() # removes ORD-004
first = pending_orders.pop(0) # removes ORD-001
# Check membership
print("ORD-002" in pending_orders) # True
# Slice: elements at index 0 and 1
print(pending_orders[0:2])
# Length
print(len(pending_orders))
# Sort in place
pending_orders.sort()
# List comprehension: apply a transformation
upper = [oid.upper() for oid in pending_orders]

Performance notes: Appending to the end is O(1) amortized. Inserting or deleting at an arbitrary position is O(n). Membership testing (in) is O(n) — use a set if you need fast membership checks.

tuple — ordered, immutable, allows duplicates

Section titled “tuple — ordered, immutable, allows duplicates”

A tuple is like a list but cannot be changed after creation. This makes it safe to use as a dictionary key and signals to readers that the values should not change.

# OrdersPortal: a 2D coordinate for a warehouse shelf location (row, column)
shelf_location = (4, 7)
row, col = shelf_location # tuple unpacking
print(f"Row {row}, Column {col}") # Row 4, Column 7
# Tuples can hold mixed types
order_summary = ("ORD-100", "shipped", 149.99)
order_id, status, amount = order_summary
# Single-element tuple needs a trailing comma
single = ("ORD-001",) # without the comma, this is just a string in parentheses
# Tuples are hashable: can be used as dict keys
locations = {(4, 7): "Shelf A", (2, 3): "Shelf B"}
print(locations[(4, 7)]) # Shelf A

Use tuples for fixed groupings of values that logically belong together — coordinates, RGB colors, database row records, function return values where multiple items are returned.

dict — key-value store, ordered (Python 3.7+), mutable

Section titled “dict — key-value store, ordered (Python 3.7+), mutable”

A dict maps unique keys to values. Keys must be hashable (strings, numbers, tuples — not lists). Since Python 3.7, dicts preserve insertion order.

# OrdersPortal: an order record
order = {
"id": "ORD-200",
"customer": "BensonCo",
"amount": 299.50,
"status": "pending",
}
# Access a value
print(order["customer"]) # BensonCo
# Safe access with a default (KeyError if key missing otherwise)
discount = order.get("discount", 0.0) # returns 0.0
# Add or update a key
order["status"] = "confirmed"
# Remove a key
removed = order.pop("discount", None) # None if key doesn't exist
# Iterate
for key, value in order.items():
print(f"{key}: {value}")
# Keys and values
print(list(order.keys()))
print(list(order.values()))
# Membership check (checks keys)
print("amount" in order) # True
# Dict comprehension
prices = {"apple": 1.20, "banana": 0.50, "cherry": 2.00}
expensive = {k: v for k, v in prices.items() if v > 1.0}
print(expensive) # {'apple': 1.2, 'cherry': 2.0}

Common patterns:

  • Use dict.get(key, default) instead of dict[key] when the key might not exist.
  • Use collections.defaultdict when you want automatic default values.
  • Use collections.Counter for frequency counting.

set — unordered, mutable, unique values only

Section titled “set — unordered, mutable, unique values only”

A set holds unique values. It has no concept of order and no indexing. Sets are optimized for membership testing and mathematical set operations.

# OrdersPortal: tags applied to products
product_tags = {"electronics", "sale", "refurbished"}
other_tags = {"sale", "new-arrival", "electronics"}
# Add and remove
product_tags.add("warranty")
product_tags.discard("refurbished") # no error if missing
# Membership — O(1) unlike list's O(n)
print("sale" in product_tags) # True
# Set operations
print(product_tags & other_tags) # intersection: {'electronics', 'sale'}
print(product_tags | other_tags) # union: all tags
print(product_tags - other_tags) # difference: in first but not second
print(product_tags ^ other_tags) # symmetric difference: in one but not both
# Remove duplicates from a list (order not preserved)
order_ids = ["ORD-1", "ORD-2", "ORD-1", "ORD-3"]
unique_ids = list(set(order_ids))

Use frozenset for an immutable, hashable set (usable as a dict key).

Type Ordered Mutable Duplicate values Hashable Typical use
list Yes Yes Yes No Sequences, queues, stacks
tuple Yes No Yes Yes Fixed groupings, dict keys, return values
dict Yes (insertion) Yes No (keys) No Key-value lookup, records
set No Yes No No Uniqueness, fast membership, set math
  • Modifying a list while iterating over it. Iterate over a copy (for item in my_list[:]) or build a new list with a comprehension.
  • Using a list for membership tests in a hot loop. x in list is O(n). Convert to a set first if you check repeatedly.
  • Forgetting the trailing comma in a single-element tuple. ("value") is just a string; ("value",) is a tuple.
  • Mutating a default argument. def f(items=[]) shares the same list across all calls. Use def f(items=None): items = items or [].
  • Using a list as a dict key. Lists are not hashable. Use a tuple instead.
Scenario Type
Ordered collection that changes (append, remove, sort) list
Fixed group of values that belong together tuple
Mapping from unique keys to values dict
Tracking which items you’ve seen; removing duplicates set
Immutable dict key that’s a compound value tuple
Counting occurrences collections.Counter

1. What is the difference between a list and a tuple in Python? A list is mutable — elements can be added, removed, or changed. A tuple is immutable — once created it cannot be modified. Tuples are hashable so they can be used as dictionary keys; lists cannot. Tuples signal to readers that the grouped values should not change, making intent clearer.

2. Why is x in some_set faster than x in some_list? Sets use a hash table internally. Computing a hash of x and looking up the bucket is O(1). Lists use linear search — every element is checked in order — so membership testing is O(n). For a list of 10,000 items, a set lookup is roughly 10,000× faster.

3. Senior scenario: an OrdersPortal service receives 100,000 order IDs per hour and must check whether each one has already been processed. What data structure would you use and why? Store processed IDs in a set. Membership testing is O(1) average case. A list would degrade to O(n) per check. If the set must persist across restarts, back it with a Redis SADD / SISMEMBER or a database unique index. Memory is the main constraint: 100,000 UUIDs at ~36 bytes each is roughly 3.6 MB — easily held in memory. For longer retention windows, use a Bloom filter to trade a small false-positive rate for much lower memory consumption.

  • Use list for ordered, changeable sequences.
  • Use tuple for fixed groupings; tuples are hashable and can be dict keys.
  • Use dict for key-value lookup; dicts preserve insertion order since Python 3.7.
  • Use set for uniqueness enforcement and fast membership testing.
  • Membership testing on a set is O(1); on a list it is O(n).