0
0
Pythonprogramming~5 mins

reversed() function in Python

Choose your learning style9 modes available
Introduction

The reversed() function helps you look at items in a list or string from the end to the start. It makes it easy to go backwards without changing the original order.

When you want to read a word or sentence backwards.
When you need to process a list starting from the last item.
When you want to check if something is the same forwards and backwards (like a palindrome).
When you want to reverse the order of items without changing the original list.
Syntax
Python
reversed(sequence)

sequence can be a list, string, tuple, or any object that supports reverse iteration.

reversed() returns an iterator, so you often convert it to a list or use it in a loop.

Examples
This prints the word 'hello' backwards as 'olleh'.
Python
for char in reversed('hello'):
    print(char, end='')
This creates a new list with the numbers in reverse order: [4, 3, 2, 1].
Python
numbers = [1, 2, 3, 4]
rev_numbers = list(reversed(numbers))
print(rev_numbers)
This prints each item in the tuple starting from the last one.
Python
tuple_data = (10, 20, 30)
for item in reversed(tuple_data):
    print(item)
Sample Program

This program reverses the string 'python' and prints 'nohtyp'.

Python
word = 'python'
reversed_word = ''.join(reversed(word))
print(reversed_word)
OutputSuccess
Important Notes

The original sequence is not changed by reversed().

To see the reversed items all at once, convert the iterator to a list or string.

Summary

reversed() lets you go through items backwards without changing the original.

It works with strings, lists, tuples, and more.

You usually use it in loops or convert it to a list or string to see all reversed items.