Python Practice › List Programs › Program 15
reversed() and reverse()
Write a Python program to reverse a list with reversed() and with reverse().
Input
[1, 2, 3, 4, 5]
Output
[5, 4, 3, 2, 1] [5, 4, 3, 2, 1]
Approach
reversed()gives an iterator;reverse()changes the list in place.
Solution
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.