Python Practice › List Programs › Program 24

sort() vs sorted()

EasyList Programs · 24 of 100

Write a Python program to sort a list with sort() and with sorted().

Advertisement
Input
[5, 2, 9, 1, 7]
Output
[1, 2, 5, 7, 9] [5, 2, 9, 1, 7]
[9, 7, 5, 2, 1]

Approach

  1. sorted() returns a new list; sort() sorts in place.

Solution

Python
numbers = [5, 2, 9, 1, 7]print(sorted(numbers), numbers)numbers.sort(reverse=True)print(numbers)
Output
[1, 2, 5, 7, 9] [5, 2, 9, 1, 7]
[9, 7, 5, 2, 1]

Line by line

Line 2

The original order is unchanged by sorted().

Line 3

sort() changes the list; reverse=True gives descending order.

Learn the concept

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

More list programs

← All 100 List Programs

Leave a Comment