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.
Create a function reverse(lst) that takes a list and returns the elements in reverse order.
Reversing list sequences is crucial for undo operations, stack data processing, and chronological sorting.
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: []
[start:stop:step][::-1]: Omitting start and stop defaults to the whole list, while step = -1 steps backward from end to start.lst.reverse() with lst[::-1]: Calling lst.reverse() reverses the list in-place and returns None! If your function returns lst.reverse(), it will return None to the caller. Always use lst[::-1] when returning a reversed list!Use [::-1] for non-mutating reversed lists. Next, let's filter out strings from a mixed list!
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.
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.
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.