PythonBuilt-in functions
reversed()
Returns an iterator that walks through a sequence from the end.
- Returns
- An iterator with the items in reverse order.
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, whilereversed()leaves it unchanged.
Related entries
#- sorted()Returns a new, sorted list built from the items of any collection.
- list.reverse()Reverses the order of the items in a list in place.
- range()Creates a sequence of integers, most often for a for loop.
- String slicing [start:stop:step]Getting fragments of a string by index.
- iter()Returns an iterator for a collection, an object that hands out its items one at a time. This is the mechanism behind the for loop.
Spotted a mistake or missing an example? Write to us.