Mastering Python Lists
A Visual Guide to Indexing & Slicing
1. Indexing: Pinpointing Elements
Dual Indexing System
Python lists can be accessed from both the beginning (positive index) and the end (negative index). This provides incredible flexibility for accessing elements regardless of list length.
Element | Positive Index | Negative Index |
---|---|---|
'A' | 0 | -5 |
'B' | 1 | -4 |
'C' | 2 | -3 |
'D' | 3 | -2 |
'E' | 4 | -1 |
0
Zero-Based Start
The first element of any Python list is always at index 0.
-1
The Last Element
The final element is always accessible at index -1.
2. Slicing: Extracting Subsequences
Slicing creates a new list from a portion of an existing one using the `list[start:end:step]` syntax. It's a powerful way to work with subsets of your data without modifying the original list.
Visualizing a Slice
This chart shows `my_list[2:7]`. Notice how the slice starts at index 2 and extracts 5 elements, stopping just before index 7.
The Golden Rule of Slicing
The `end` index is always exclusive.
The slice includes elements up to, but not including, the element at the `end` index. This is a crucial detail to avoid off-by-one errors.
# Create a shallow copy
new_list = old_list[:]
# Get every other element
evens = my_list[::2]
# Reverse the list
reversed_list = my_list[::-1]
3. Slice Assignment: Powerful In-Place Modification
This is where lists show their true power. By using a slice on the left side of an assignment, you can modify the list in-place, changing its contents and even its length dynamically.
Replace & Shrink
Replace a slice with a shorter sequence. The list contracts.
nums = [10, 20, 30, 40, 50]
nums[1:4] = [99, 88]
↓
[10, 99, 88, 50]
Insert Elements
Assign to an empty slice (`[i:i]`) to insert without replacing.
nums = [10, 50]
nums[1:1] = [20, 30, 40]
↓
[10, 20, 30, 40, 50]
Delete Elements
Assign an empty list to a slice to delete elements, or use `del`.
nums = [10, 20, 30, 40, 50]
del nums[1:4]
↓
[10, 50]
4. Core Concepts & Common Pitfalls
Mutability: Lists vs. Tuples
Lists are mutable (changeable), while types like tuples and strings are immutable (not changeable). This is the key reason write operations work on lists.
📝
List (Mutable)
✓ Can be changed
🔒
Tuple (Immutable)
✗ Cannot be changed
Aliasing vs. Copying
Assignment (`b = a`) creates an alias (two names, one list). Slicing (`c = a[:]`) creates a true, independent copy.
b = a (Alias)
c = a[:] (Copy)
Stepped Slice Assignment
When using a `step` in a slice assignment, the replacement sequence must be the exact same length as the slice it is replacing.
Common Errors to Avoid
⚠️
IndexError
Occurs when you try to access or assign to an index that doesn't exist (it's outside the list's bounds).
⚠️
ValueError
In this context, it's raised when the length of the new sequence doesn't match the length of a stepped slice during assignment.