Reverse a List in Python
Quick Overview
`[::-1]` returns a reversed copy, `.reverse()` mutates in place and returns `None`, and `reversed()` gives a lazy iterator that copies nothing. Three spellings, three different costs.
Deep Dive
1. The Challenge: Reversing Order
Create a function reverse(lst) that takes a list and returns the elements in reverse order.
2. Why It Matters
Reversing list sequences is crucial for undo operations, stack data processing, and chronological sorting.
3. The Python Solution
Use Python list slicing with step -1 (lst[::-1]):
def reverse(lst):
return lst[::-1]
# Testing our function
print(reverse([1, 2, 3, 4])) # Output: [4, 3, 2, 1]
print(reverse([9, 9, 2, 3, 4])) # Output: [4, 3, 2, 9, 9]
print(reverse([])) # Output: []
4. Understanding Slice Syntax [start:stop:step]
[::-1]: Omitting start and stop defaults to the whole list, whilestep = -1steps backward from end to start.- Non-mutating: Slicing returns a new list without modifying the original source list!
5. Common Mistakes
- Confusing
lst.reverse()withlst[::-1]: Callinglst.reverse()reverses the list in-place and returnsNone! If your function returnslst.reverse(), it will returnNoneto the caller. Always uselst[::-1]when returning a reversed list!
6. Next Steps
Use [::-1] for non-mutating reversed lists. Next, let's filter out strings from a mixed list!
Next Up in Python Beginner Practice & Core Problem Solving
Return the Sum of Two Numbers
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
Convert Minutes into Seconds
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
Calculate the Area of a Triangle
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.