Python Reference ยท Built-in Functions
Python reversed() function
Reference for Python reversed(): iterate sequences backward without copying, how it differs from list.reverse() and slicing, and supporting __reversed__.
The built-in reversed() function returns an iterator that yields the items of a sequence from last to first. It does not modify the original and does not copy the data; it simply walks the sequence backward, using the index.
Because the result is an iterator, wrap it in list(), "".join() or a for loop to see the items. It accepts sequences (lists, tuples, strings, ranges) and any object that defines __reversed__(), and it also works on dictionaries (Python 3.8+).
list(reversed([1, 2, 3])) # [3, 2, 1] "".join(reversed("abc")) # "cba"
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
reversed(seq)
| Name | Description |
|---|---|
seq |
An object with __reversed__(), or a sequence with __len__() and __getitem__() (integer indexes from 0). |
Return value: a reverse iterator (a list_reverseiterator, reversed or similar object).
Raises: TypeError if the argument is not reversible, for example a set, a generator or an iterator.
Usage notes
- No copy, no mutation.
reversed(items)is cheap for any size. Compareitems[::-1], which builds a new list, anditems.reverse(), which reverses in place and returnsNone. - One pass only. The iterator is exhausted after you use it. Create a new one, or convert to a list, to reuse it.
- Not sorting.
reversedflips the current order. To order from largest to smallest usesorted()withreverse=True. - Generators, sets and other iterators cannot be reversed because they lack order or random access. Make a list first:
reversed(list(gen)). - Strings:
reversed("abc")yields characters; join them back with"".join(...), or just slicetext[::-1]. - Dictionaries iterate in reverse insertion order (Python 3.8+), because dicts remember insertion order.
- Combine with
enumeratefor numbered backward loops; for indexes counting down on the original positions userange(len(items) - 1, -1, -1). - Custom classes: define
__reversed__()to supply an efficient backward iterator, or provide__len__()and__getitem__()and the default support will work. - Unicode. Reversing a string reverses code points, which can detach combining accents from their base letters.
Related
sorted(),range(),enumerate(),iter(),zip()- Lessons: Lists, List methods, Slicing