Lists and Tuples: Indexing, Slicing and Mutability
Storing one value per variable works for small scripts, but real applications handle collections of data: a queue of support tickets, a list of active IP addresses or a fixed pair of database coordinates. Python provides two built-in ordered sequence types for this job: lists (list) and tuples (tuple). Choosing the right one—and understanding how Python handles mutable objects in memory—is a core milestone for every Python developer.
Lists vs Tuples: What Is the Difference?
| Feature | List (list) |
Tuple (tuple) |
|---|---|---|
| Syntax | Square brackets: ["web-01", "web-02"] |
Parentheses: ("10.0.0.1", 5432) |
| Mutability | Mutable: Add, remove or change elements in place | Immutable: Elements cannot be altered after creation |
| Best Used For | Collections that grow, shrink or change over time | Fixed records that belong together (such as (hostname, port)) |
Indexing, Slicing and Modifying Lists
active_nodes = ["node-a", "node-b", "node-c"]
# Replace an element in place
active_nodes[1] = "node-b-patched"
# Add elements
active_nodes.append("node-d") # Adds to the end
active_nodes.insert(0, "node-master") # Inserts at index 0
# Remove elements
removed_node = active_nodes.pop() # Removes and returns last item ("node-d")
active_nodes.remove("node-c") # Removes first matching value
print(active_nodes)
# Output: ['node-master', 'node-a', 'node-b-patched']
Essential List Operations and Sorting
| Operation / Method | Modifies in Place? | What It Does |
|---|---|---|
items.append(x) |
Yes (returns None) |
Adds single item x to the end of the list |
items.extend(iterable) |
Yes (returns None) |
Appends all elements from another list or iterable |
items.sort() |
Yes (returns None) |
Sorts the existing list in place |
sorted(items) |
No (returns new list) | Leaves original list untouched and returns a newly sorted list |
len(items) |
No | Returns the number of items in the list or tuple |
Tuple Unpacking: Clean Multi-Variable Assignment
db_endpoint = ("db-prod.internal.net", 5432, "read_only")
# Unpack into three distinct variables
host, port, mode = db_endpoint
print(f"Connecting to {host} on port {port} ({mode} mode)")
A Short Example: Managing an Incident Ticket Queue
resolution_times = [42, 15, 120, 8, 65, 30]
fastest_to_slowest = sorted(resolution_times)
print(f"Original Order: {resolution_times}")
print(f"Fastest: {fastest_to_slowest[0]}m | Slowest: {fastest_to_slowest[-1]}m")
print(f"Top 3 Fastest: {fastest_to_slowest[:3]}")
Common Mistakes
- Assigning the result of
.append()or.sort(): In-place methods returnNone. Writingmy_list = my_list.append("x")overwrites your list withNone. - Copying a list with
=(Aliasing Bug): Writingb = apoints both names to the same list in memory. Useb = a.copy()to create an independent copy. - Forgetting the trailing comma in a single-item tuple: Write
t = ("srv-01",)with a comma, not("srv-01").
Key takeaways
- Lists (
[...]) are mutable sequences for dynamic collections; tuples ((...)) are immutable sequences for fixed records. - In-place list methods like
.append()and.sort()returnNone. - Use
.copy()when you need an independent duplicate of a list. - Use tuple unpacking (
host, port = endpoint) for clean multi-variable assignment.