reversed()

Returns an iterator that walks through a sequence from the end.

Returns
An iterator with the items in reverse order.
On this page

Example

#
Python
steps = ["start", "learning", "project", "job"]

for step in reversed(steps):
    print(step)

print(list(reversed(range(1, 4))))
print("".join(reversed("kayak")))
Resultsaved result, you can check it
job
project
learning
start
[3, 2, 1]
kayak

Definition and usage

#

The reversed() function returns an iterator that gives a sequence's items in reverse order. It doesn't create a copy and doesn't change the original.

It works on sequences with a known length and indexes: lists, tuples, strings, and range objects. It does not work on sets, because they have no order.

For strings, the slice text[::-1] is used more often, since it returns the reversed string right away. reversed() is handy in loops, when you want to go from the end without creating a new list.

Syntax

#
Syntax
reversed(seq)

Parameters

#
  • seq

    a list, tuple, string, or range

    The sequence to walk through from the end.

Good practices

#
  • The simplest way to reverse a string is text[::-1].
  • The list.reverse() method reverses a list in place, while reversed() leaves it unchanged.

Related entries

#

Spotted a mistake or missing an example? Write to us.