Python Practice › List Programs › Program 15

reversed() and reverse()

EasyList Programs · 15 of 100

Write a Python program to reverse a list with reversed() and with reverse().

Advertisement
Input
[1, 2, 3, 4, 5]
Output
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]

Approach

  1. reversed() gives an iterator; reverse() changes the list in place.

Solution

Python
numbers = [1, 2, 3, 4, 5]print(list(reversed(numbers)))numbers.reverse()print(numbers)
Output
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]

Line by line

Line 2

reversed() returns an iterator, so wrap it in list() to see the items.

Line 3

reverse() returns None and reverses numbers itself.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Leave a Comment