Python reversed()
Anonymous contributor
Published Jul 14, 2021Updated Aug 22, 2023
Contribute to Docs
The reversed() function takes in an iterable object, such as a list, string, or a tuple and returns a reversed iterator object.
Syntax
reversed(iterator)
Example 1
Because the reversed() function returns an iterator object, in order to access the content, it is necessary to iterate over the object when printing:
counting = ["one", "two", "three"]blast_off = reversed(counting)for num in blast_off:print(num, end=" ")# Output: three two one
Example 2
The example below reverses the elements of a list.
Note: To simply reverse an existing list rather than return an iterator object, Python has a
list.reverse()method:
counting = ["one", "two", "three"]blast_off = reversed(counting)print(blast_off) # Output: <list_reverseiterator object at 0x7ff4f6a1dfa0>counting.reverse()print(counting) # Output: ['three', 'two', 'one']
Example 3
Because strings are also iterable objects, reversed() can also be used on strings.
new = reversed("stressed")for letter in new:print(letter, end="")# Output: desserts
Codebyte Example
Tuples are iterable objects too, hence reversed() can be used on tuples as well.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Learn to analyze and visualize data using Python and statistics.
- Includes 8 Courses
- With Certificate
- Intermediate.13 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours