Python Program to Sort a List

1. Introduction

Sorting is a fundamental operation in programming. In Python, lists are commonly used structures, and sorting them is a frequent necessity for tasks like data analysis, searching, and algorithm optimization.

Definition

Sorting a list involves rearranging its elements into a specific order, typically in ascending or descending sequence. Python provides built-in methods to perform sorting efficiently.

2. Program Steps

1. Define an unsorted list of numbers.

2. Use the sort() method to sort the list in-place, or use the sorted() function to return a new sorted list.

3. Print the sorted list.

3. Code Program

# Step 1: Define an unsorted list of numbers
unsorted_list = [34, 1, 17, 8, 3]

# Step 2: Use the sort() method to sort the list in-place
unsorted_list.sort()

# Step 3: Print the sorted list
print(f"Sorted list (ascending): {unsorted_list}")

# Step 2 alternative: Use the sorted() function to get a new sorted list
sorted_list = sorted(unsorted_list, reverse=True)  # For descending order

# Step 3 alternative: Print the new sorted list
print(f"Sorted list (descending): {sorted_list}")

Output:

Sorted list (ascending): [1, 3, 8, 17, 34]
Sorted list (descending): [34, 17, 8, 3, 1]

Explanation:

1. unsorted_list is created containing a series of integers in no particular order.

2. The sort() method is used to sort unsorted_list. It sorts the list in-place, meaning unsorted_list is modified directly.

3. The first print statement outputs the list after the sort() method has been applied, resulting in an ascending order sequence.

4. sorted_list is created using the sorted() function, which returns a new list. The reverse=True argument sorts the numbers in descending order.

5. The second print statement displays sorted_list, showing the numbers sorted in descending order.

Comments