Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Python reversed()
In this tutorial, you will learn about Python reversed() with the help of examples.
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?