Python Reference ยท Lists, Tuples and Ranges
Python list.reverse() method
Reference for Python list.reverse(): reverse a list in place, why it returns None, and how it differs from reversed() and the [::-1] slice.
The list.reverse() method reverses the order of the items in a list, in place. The first item becomes the last, the second becomes the second to last, and so on. The list object stays the same; only its contents are rearranged.
Because the list is changed directly, reverse() returns None. If you need a reversed copy and want to keep the original, use reversed() or the slice [::-1] instead.
numbers = [1, 2, 3] numbers.reverse() print(numbers) # [3, 2, 1]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
list.reverse()
reverse() takes no arguments.
Return value: None. The list is modified in place.
Raises: nothing for a normal list. Calling it on a tuple or string raises AttributeError, because those types have no reverse() method.
Usage notes
- A common mistake is
items = items.reverse(). That replaces your list withNone. Callitems.reverse()on its own line. - Other names for the same list see the change. If two variables refer to one list, both show the reversed order.
- Reversing is not sorting.
reverse()only flips the current order. To sort in descending order uselist.sort()withreverse=True. - Need a copy?
items[::-1]andlist(reversed(items))both build a new list. The built-inreversed()on its own returns a lazy iterator, which is cheaper when you only want to loop. - Works on any list, including lists of lists. Nested lists are not reversed; only the outer order changes.
- Speed:
reverse()runs in linear time and needs no extra memory, since it swaps items inside the existing list. - Strings and tuples have no
reverse()method. Use a slice orreversed(), for example"abc"[::-1].
Related
list.sort(),reversed(),sorted(), slicing,list- Lessons: Lists, List methods