How to use reversed() in Python

The ‘reversed()‘ function in Python can be used to reverse an iterable (list, tuple, string, etc.):

1. Reverse a list:

my_list = ["a", "b", "c", "d", "e"]

reversed_list = list(reversed(my_list))

print(reversed_list)

The result:

['e', 'd', 'c', 'b', 'a']

2. Reverse a tuple:

my_tuple = ("a", "b", "c", "d", "e")

reversed_tuple = tuple(reversed(my_tuple))

print(reversed_tuple)

The result:

('e', 'd', 'c', 'b', 'a')

3. Reverse a string:

my_string = "abcde"

reversed_string = "".join(reversed(my_string))

print(reversed_string)

The result:

edcba

4. Reverse with a for loop:

my_list = ["a", "b", "c", "d", "e"]

for i in reversed(my_list):
print(i)

The result:

e
d
c
b
a

5. Reverse with enumerate():

my_list = ["a", "b", "c", "d", "e"]

for idx, i in enumerate(reversed(my_list)):
print(f"Index {len(my_list) - idx - 1}: {i}")

The result:

Index 4: e
Index 3: d
Index 2: c
Index 1: b
Index 0: a

6. Reverse with a range():

my_range = range(1, 6)

reversed_range = list(reversed(my_range))

print(reversed_range)

The result:

[5, 4, 3, 2, 1]

Additional topics

Leave a Comment