Sorting Lists in Python

You can sort lists using the sort() method or the built-in sorted() function.

Using sort() Method

Example: Sorting a List of Numbers

# Sorting a list
numbers = [5, 2, 9, 1, 5, 6]
print("Original List:", numbers)
numbers.sort()
print("Sorted List:", numbers)

Output

Original List: [5, 2, 9, 1, 5, 6]

Sorted List: [1, 2, 5, 5, 6, 9]

Explanation: The sort() method sorts the list in ascending order.

Using sorted() Function

Example: Sorting a List in Descending Order

# Using sorted() function
numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers = sorted(numbers, reverse=True)
print("Original List:", numbers)
print("Sorted List (Descending):", sorted_numbers)

Output

Original List: [5, 2, 9, 1, 5, 6]

Sorted List (Descending): [9, 6, 5, 5, 2, 1]

Explanation: The sorted() function returns a new sorted list, leaving the original list unchanged.