Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Sorting

Sorting is an essential operation when working with lists in Python. Python provides a simple and powerful way to sort lists using built-in methods.

Sorting a List

Python has a built-in .sort() method for lists, which sorts the list in place (modifies the original list).

numbers = [5, 2, 9, 1, 5, 6]
numbers.sort()
print(numbers)  # Output: [1, 2, 5, 5, 6, 9]

The .sort() method sorts the list in ascending order by default.

Sorting in Descending Order

To sort a list in descending order, pass reverse=True to the .sort() method:

numbers = [5, 2, 9, 1, 5, 6]
numbers.sort(reverse=True)
print(numbers)  # Output: [9, 6, 5, 5, 2, 1]

Using the sorted() Function

Python also provides the sorted() function, which returns a new sorted list instead of modifying the original one.

numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # Output: [1, 2, 5, 5, 6, 9]
print(numbers)  # Original list remains unchanged

You can also use sorted() with reverse=True:

sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc)  # Output: [9, 6, 5, 5, 2, 1]

Sorting Strings

Lists of strings can also be sorted alphabetically:

names = ["Charlie", "Alice", "Bob"]
names.sort()
print(names)  # Output: ['Alice', 'Bob', 'Charlie']

Custom Sorting with key

You can use a custom function for sorting using the key parameter. For example, sorting words by their length:

words = ["banana", "apple", "cherry", "date"]
words.sort(key=len)
print(words)  # Output: ['date', 'apple', 'banana', 'cherry']

Exercise: Try It Yourself!

  1. Create a list of numbers and sort it in ascending and descending order.
  2. Sort a list of names alphabetically.
  3. Use the sorted() function instead of .sort().
  4. Create a list of words and sort them based on their length.