Core Data Structures in Python: list, tuple, dict, set
What you’ll learn
Section titled “What you’ll learn”- 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
OrdersPortalinventory and order system.
Summary
Section titled “Summary”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 IDspending_orders = ["ORD-001", "ORD-002", "ORD-003"]
# Access by index (0-based)print(pending_orders[0]) # ORD-001print(pending_orders[-1]) # ORD-003 (last element)
# Add to the endpending_orders.append("ORD-004")
# Insert at a positionpending_orders.insert(1, "ORD-001B")
# Remove by valuepending_orders.remove("ORD-001B")
# Remove by index and return the valuelast = pending_orders.pop() # removes ORD-004first = pending_orders.pop(0) # removes ORD-001
# Check membershipprint("ORD-002" in pending_orders) # True
# Slice: elements at index 0 and 1print(pending_orders[0:2])
# Lengthprint(len(pending_orders))
# Sort in placepending_orders.sort()
# List comprehension: apply a transformationupper = [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 unpackingprint(f"Row {row}, Column {col}") # Row 4, Column 7
# Tuples can hold mixed typesorder_summary = ("ORD-100", "shipped", 149.99)order_id, status, amount = order_summary
# Single-element tuple needs a trailing commasingle = ("ORD-001",) # without the comma, this is just a string in parentheses
# Tuples are hashable: can be used as dict keyslocations = {(4, 7): "Shelf A", (2, 3): "Shelf B"}print(locations[(4, 7)]) # Shelf AUse 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 recordorder = { "id": "ORD-200", "customer": "BensonCo", "amount": 299.50, "status": "pending",}
# Access a valueprint(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 keyorder["status"] = "confirmed"
# Remove a keyremoved = order.pop("discount", None) # None if key doesn't exist
# Iteratefor key, value in order.items(): print(f"{key}: {value}")
# Keys and valuesprint(list(order.keys()))print(list(order.values()))
# Membership check (checks keys)print("amount" in order) # True
# Dict comprehensionprices = {"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 ofdict[key]when the key might not exist. - Use
collections.defaultdictwhen you want automatic default values. - Use
collections.Counterfor 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 productsproduct_tags = {"electronics", "sale", "refurbished"}other_tags = {"sale", "new-arrival", "electronics"}
# Add and removeproduct_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 operationsprint(product_tags & other_tags) # intersection: {'electronics', 'sale'}print(product_tags | other_tags) # union: all tagsprint(product_tags - other_tags) # difference: in first but not secondprint(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).
Comparison table
Section titled “Comparison table”| 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 |
Common mistakes
Section titled “Common mistakes”- 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 listis 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. Usedef f(items=None): items = items or []. - Using a list as a dict key. Lists are not hashable. Use a tuple instead.
When to use each type
Section titled “When to use each type”| 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 |
Interview questions
Section titled “Interview questions”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.
Key takeaways
Section titled “Key takeaways”- 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).
Related pages
Section titled “Related pages”- Python variables and types — primitive types and mutability
- collections module — Counter, defaultdict, deque, OrderedDict
- List comprehensions — building lists concisely
- Python basics — quick syntax reference
Official references
Section titled “Official references”- Python docs: Data Structures — official tutorial chapter
- Python docs: Built-in Types — full type reference
- Python docs: collections module — specialized container types