Python: Sort a List of Integers in Descending Order

1. Introduction

Sorting is one of the fundamental operations in computer science. In Python, lists have a built-in method called sort(), which allows us to easily sort a list in ascending or descending order. In this post, we will use the sort() method to sort a list of integers in descending order.

2. Program Overview

Our program will prompt the user to enter a series of integers, separated by spaces. The program will then convert this input into a list of integers and sort this list in descending order. Finally, the sorted list will be displayed to the user.

3. Code Program

# Get input from user
numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))

# Sort the list in descending order
numbers.sort(reverse=True)

# Display the sorted list
print("Sorted numbers in descending order:", numbers)

Output:

Enter numbers separated by spaces: 20 10 30 5 1
Sorted numbers in descending order: [30, 20, 10, 5, 1]

4. Step By Step Explanation

1. The input() function is used to take a string input from the user. We expect the user to input numbers separated by spaces, e.g., "4 7 1 9 3".

2. The split() method is used to split the string input based on spaces, resulting in a list of strings: ['4', '7', '1', '9', '3'].

3. The map() function is used to convert each string in the list into an integer. The list() function then converts the map object into a list of integers: [4, 7, 1, 9, 3].

4. The sort() method of the list object is then used to sort the list of integers. By setting the reverse parameter to True, we ensure the list is sorted in descending order.

5. Finally, the sorted list is printed to the console using the print() function.

Comments