Topic 45 of 64
List Slicing Formulas
Overview
Slicing extracts sublists using list[start:stop:step] syntax. It creates a new list (shallow copy) and is one of Python's most powerful and elegant features for data manipulation.
Syntax
python
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
nums[2:5] # [2, 3, 4] start=2, stop=5 (exclusive)
nums[:3] # [0, 1, 2] from beginning
nums[7:] # [7, 8, 9] to end
nums[::2] # [0, 2, 4, 6, 8] every 2nd element
nums[::-1] # [9, 8, 7, ..., 0] reversed!
nums[-3:] # [7, 8, 9] last 3 elements
# Copy a list
copy = nums[:]Common Pitfalls
- Slicing never raises IndexError even for out-of-range indices — it silently returns what's available.
- Slicing returns a shallow copy — modifying nested objects in the slice affects the original.
- Interview tip: nums[::-1] is more Pythonic than reversed(list(nums)) for reversing — but reversed() is memory-efficient for iteration.
Real-World Example
Paginate a list of results using slice arithmetic
example
python
def paginate(items: list, page: int, size: int) -> list:
start = (page - 1) * size
end = start + size
return items[start:end]
data = list(range(1, 21)) # [1, 2, ..., 20]
print(paginate(data, 2, 5)) # [6, 7, 8, 9, 10]
print(paginate(data, 4, 5)) # [16, 17, 18, 19, 20]