Lists & Tuples
Overview
Lists are mutable sequences. Tuples are immutable sequences. Choose the right collection based on your need for changes.
Learning Objectives
- Manage list insertions, updates, and sorting.
- Use tuples to store fixed values.
- Select the correct type based on data mutability.
Concept Explanation
Lists are mutable, meaning you can update, add, or delete elements in-place. Tuples are immutable and cannot be changed after creation. Because tuples are fixed, they use less memory and can be used as dictionary keys.
Code Examples
Example 1 — Basics
This example introduces the fundamental syntax and concepts.
my_list = [10, 20]
my_tuple = (10, 20)
Example 2 — Everyday Usage
This example demonstrates a realistic scenario handling business parameters.
# Edit inventory list items
inventory = ['books', 'pens']
inventory.append('pencils')
inventory.sort()
print(inventory)
Example 3 — Advanced Example
This example shows clean, production-grade code structure following senior development standards.
# Using tuples as immutable keys inside dictionary lookups
registry = {}
coord_key = (40.7128, -74.0060)
registry[coord_key] = 'New York City'
print(registry.get(coord_key))
Visual Flow
The following execution flow represents the step-by-step evaluation inside the interpreter:
Append Item → Check capacity → Resize if needed → Insert value reference
Common Mistakes
Review these common pitfalls when working with this topic:
- Using list.pop(0) to dequeue items (this shifts all elements in memory, which is slow; use collections.deque instead).
- Forgetting a comma when creating single-item tuples (e.g. t = (1) is an int; use t = (1,) instead).
- Modifying list sizes inside loops.
- Expecting tuple items to be modifiable.
Best Practices
Enforce these Pythonic best practices in your codebase:
items = [1, 2, 3]
items.pop(0) # Slow index shifting
from collections import deque
q = deque([1, 2, 3])
q.popleft() # Fast double-ended pops
Performance Notes
Keep these optimization guidelines in mind for performance-sensitive hotpaths:
- List appends are O(1) amortized, but list inserts at index 0 run in O(N) time because all other elements must be shifted in memory.
Quick Revision
Use these key summaries for last-minute revision:
- Lists are mutable and resize dynamically.
- Tuples are immutable fixed-size sequences.
- Single-item tuples require a trailing comma.
- deque is better than list for FIFO queues.
- Tuples are hashable if all their items are hashable.
DataPlayArena Technical Editorial Board
Curated & maintained by enterprise data platform engineers with 10+ years in distributed systems.
Runtime Verification Standards: Every code example, query, and architecture diagram in this tutorial is compiled and verified against real runtimes (Apache Spark 3.5, Python 3.11, PostgreSQL, and DuckDB). If you spot any errata or want to suggest improvements, please submit feedback.