Takes in an iterator object, such as a list or string, and returns a reversed iterator object.
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
To simply reverse an existing list rather than return an iterator object, Python has a
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']
Because strings are also iterator objects,
reversed() can also be used on strings.
new = reversed("stressed")for letter in new:print(letter, end="")# Output: desserts
Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.
Learn Python on Codecademy
Analyze Data with PythonLearn to analyze and visualize data using Python and statistics.
Includes 8 Courses