How do you reverse a list in Python?
Short answer: call nums.reverse() to reverse the list itself, or use nums[::-1] to get a reversed copy and keep the original. To loop backwards without making a copy, use reversed(nums).
nums = [1, 2, 3, 4, 5]
nums.reverse()
print(nums) # [5, 4, 3, 2, 1]
print(nums[::-1]) # [1, 2, 3, 4, 5] a new listreverse() returns None, so never write nums = nums.reverse(). Strings have no reverse(), but "hello"[::-1] returns 'olleh'.
reverse() changes the list itself, [::-1] returns a new reversed list and also works with strings.
Every way to reverse in Python
| What you want | Code | Changes the original | Returns |
|---|---|---|---|
| Reverse the list itself | nums.reverse() | Yes | None |
| A reversed copy | nums[::-1] | No | A new list |
| Loop backwards | for n in reversed(nums): | No | An iterator |
| A reversed copy from the iterator | list(reversed(nums)) | No | A new list |
| Sort from largest to smallest | sorted(nums, reverse=True) | No | A new sorted list |
| Reverse a string | "hello"[::-1] or "".join(reversed("hello")) | No (strings can't change) | 'olleh' |
| Reverse the words of a sentence | " ".join(reversed(text.split())) | No | 'Python love I' |
| Reverse a tuple | (1, 2, 3)[::-1] | No | (3, 2, 1) |
| Count down | range(5, 0, -1) | — | 5, 4, 3, 2, 1 |
Reverse a list in place with reverse()
reverse() flips the order of the list you call it on. It doesn't create a new list and it returns None:
nums = [1, 2, 3, 4, 5]
result = nums.reverse()
print(nums) # [5, 4, 3, 2, 1]
print(result) # NoneEvery variable that points to that list sees the change:
a = [1, 2, 3]
b = a
a.reverse()
print(b) # [3, 2, 1]Use it when you don't need the original order any more. It is also the fastest option: in a test with a million numbers, reverse() took about 0.5 ms and [::-1] about 4 ms.
