Yandex

Python reversed() Function – Reverse Iterables Easily



Python reversed() Function

The reversed() function in Python returns an iterator that accesses the given sequence in the reverse order. It is commonly used to loop through lists or other sequences from the end to the beginning.

Syntax

reversed(sequence)

Parameters:

  • sequence – A sequence that supports reverse iteration (like list, tuple, string, or a user-defined class with __reversed__()).

Returns:

  • An iterator that returns the elements in reverse order.

Example 1: Reversing a List

numbers = [1, 2, 3, 4, 5]
for num in reversed(numbers):
    print(num)
5
4
3
2
1

Example 2: Reversing a String

text = "hello"
for char in reversed(text):
    print(char)
o
l
l
e
h

Example 3: Convert Reversed Iterator to List

items = ['a', 'b', 'c']
rev_items = list(reversed(items))
print(rev_items)
['c', 'b', 'a']

Use Cases of reversed()

  • To iterate backward in loops
  • To reverse a string or list without modifying the original
  • In problems involving palindromes or reverse traversal

Important Notes

  • reversed() does not return a reversed list directly — it returns an iterator.
  • You need to convert it to list() or tuple() if you want to store or print the reversed result directly.

Common Mistakes

  • Using reversed() on non-sequence types like sets or dictionaries will raise a TypeError.
  • To reverse those, you can convert them to a list first: reversed(list(my_set))

Interview Tip

In interviews, use reversed() when you're asked to check for palindromes or reverse iteration in loops. It's cleaner and more readable than using indexes.

Summary

  • reversed() returns an iterator for reverse traversal.
  • Works with lists, tuples, strings, and custom objects with __reversed__().
  • Use list(reversed(...)) to get a reversed list.

Practice Problem

Write a program that checks if a word is a palindrome (reads the same backward).

word = input("Enter a word: ")
if list(word) == list(reversed(word)):
    print("It's a palindrome!")
else:
    print("Not a palindrome.")


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M