Skip to content
Tutorials Center
My learning

Topics

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+).

Python
list(reversed([1, 2, 3]))   # [3, 2, 1]
"".join(reversed("abc"))    # "cba"

Try it

Python Going backward

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.

Python Dicts, generators and the alternatives

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

Python
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. Compare items[::-1], which builds a new list, and items.reverse(), which reverses in place and returns None.
  • 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. reversed flips the current order. To order from largest to smallest use sorted() with reverse=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 slice text[::-1].
  • Dictionaries iterate in reverse insertion order (Python 3.8+), because dicts remember insertion order.
  • Combine with enumerate for numbered backward loops; for indexes counting down on the original positions use range(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.