Python reversed()

The reversed() function returns an iterator object that provides access to the elements of an iterable (list, tuple, string, etc.) in reverse order.

Example

string = 'Python'

result = reversed(string)

# convert the iterator to list and print it
print(list(result))

# Output: ['n', 'o', 'h', 't', 'y', 'P']

reversed() Syntax

The syntax of reversed() is:

reversed(iterable)

The reversed() function takes a single argument.

  • iterable - an iterable such as list, tuple, string, dictionary, etc.

reversed() Return Value

The reversed() method returns an iterator object.

Note: Iterator objects can be easily converted into sequences such as lists and tuples. They can also be directly iterated over using a loop.


Example 1: Access Items in Reversed Order

text = 'cad'

# access items of the string in reversed order
for char in reversed(text):
    print(char)

Output

d
a
c

Example 2: Reverse Dictionary Keys

country_capitals = {
  'England': 'London',
  'Canada': 'Ottawa', 
  'Germany': 'Berlin'
}

# access keys in reversed order
# and convert it to a tuple
country = tuple(reversed(country_capitals))
print(country)

Output

('Germany', 'Canada', 'England')

Also Read:

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community