reversed()
Gives the items of a list, string, range or dictionary in reverse order, one by one, without copying or changing the original.
reversed(seq)reversed() walks through a sequence from the last item to the first. It is perfect in a loop: for x in reversed(items):.
It does not build a new list. It returns a reverse iterator, a small object that hands out the items backwards on demand. Wrap it in list() to get a list, or in "".join(...) to get a string.
Two things to know. An iterator can be used only once: after one loop it is empty. And reversed() needs something with an order and a length, such as a list, tuple, string, range or dictionary; a set or a generator raises TypeError.
Parameters
| Parameter | What it is |
|---|---|
seqrequired | A sequence: list, tuple, string, range, or (from Python 3.8) a dictionary or its keys, values or items. |
Return value
A reverse iterator. It prints as something like <list_reverseiterator object at 0x...>, so turn it into a list to see the items.
Examples
1Reverse a list and a string
print(list(reversed([1, 2, 3, 4])))
print("".join(reversed("stressed")))
print(tuple(reversed(("a", "b"))))[4, 3, 2, 1]
desserts
('b', 'a')2Loop backwards
steps = ["unpack", "assemble", "paint"]
for step in reversed(steps):
print("Undo:", step)Undo: paint Undo: assemble Undo: unpack
3Count down with a range
for n in reversed(range(1, 6)):
print(n, end=" ")
print("go!")5 4 3 2 1 go!
4Latest entries first from a dictionary
log = {"08:00": "start", "09:30": "meeting", "12:00": "lunch"}
for time in reversed(log):
print(time, log[time])12:00 lunch 09:30 meeting 08:00 start
Dictionaries remember the order keys were added, and reversed() walks it backwards (Python 3.8+).
5The original list does not change
queue = ["Ana", "Ben", "Chen"]
backwards = list(reversed(queue))
print(backwards)
print(queue)
print(queue[::-1])['Chen', 'Ben', 'Ana'] ['Ana', 'Ben', 'Chen'] ['Chen', 'Ben', 'Ana']
The slice [::-1] also makes a reversed copy. queue.reverse() would change queue itself.
Common mistakes
Using the iterator twice
After the first pass, the iterator is used up and gives nothing. Store a list if you need the items more than once.
r = reversed([1, 2, 3])
print(list(r))
print(list(r))[3, 2, 1] []
Reversing a set
A set has no order, so there is nothing to reverse. Sort it first.
colors = {"red", "blue", "green"}
try:
reversed(colors)
except TypeError:
print("TypeError: a set cannot be reversed")
print(sorted(colors, reverse=True))TypeError: a set cannot be reversed ['red', 'green', 'blue']
Printing reversed() directly
print(reversed(items)) shows the iterator object and a memory address, not the items. Use print(list(reversed(items))).
Questions people ask
How do I reverse a list in Python?
items.reverse() changes the list itself; items[::-1] and list(reversed(items)) give a reversed copy.
How do I reverse a string?
text[::-1] or "".join(reversed(text)). Strings have no .reverse() method.
Is reversed() faster than [::-1]?
For looping, reversed() uses almost no extra memory because it makes no copy. For a reversed copy, [::-1] is fine and a bit faster.