Skip to main content

How to sort a list in Python

How to sort a list in Python.

Here's a step-by-step tutorial on how to sort a list in Python:

  1. Create a list: First, we need a list to sort. Let's say we have a list of numbers, numbers = [4, 2, 1, 3].

  2. Using the sorted() function: The simplest way to sort a list in Python is by using the sorted() function. This function takes an iterable (like a list) as an argument and returns a new sorted list. We can assign this sorted list to a new variable or overwrite the original list.

   sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 3, 4]

In this example, sorted_numbers will contain the sorted version of the numbers list.

Note: The sorted() function does not modify the original list. It returns a new sorted list.

  1. Using the sort() method: Another way to sort a list is by using the sort() method. This method sorts the list in-place, meaning it modifies the original list directly without creating a new list.
   numbers.sort()
print(numbers) # Output: [1, 2, 3, 4]

In this example, numbers is sorted directly using the sort() method.

Note: Unlike the sorted() function, the sort() method does not return a new list. It sorts the list in-place.

  1. Sorting in descending order: By default, both the sorted() function and the sort() method sort the list in ascending order. If you want to sort the list in descending order, you can pass an additional argument reverse=True.
   sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers) # Output: [4, 3, 2, 1]

numbers.sort(reverse=True)
print(numbers) # Output: [4, 3, 2, 1]

In these examples, the reverse=True argument is used to sort the list in descending order.

  1. Sorting complex objects: If you have a list of complex objects (e.g., dictionaries or custom objects), you can specify a sorting key using the key parameter. The key can be a function that returns a value to sort by.

    Let's say we have a list of dictionaries representing students, and we want to sort them by their age:

   students = [
{"name": "Alice", "age": 20},
{"name": "Bob", "age": 18},
{"name": "Charlie", "age": 22}
]

sorted_students = sorted(students, key=lambda x: x["age"])
print(sorted_students)

Output:

   [{'name': 'Bob', 'age': 18}, {'name': 'Alice', 'age': 20}, {'name': 'Charlie', 'age': 22}]

In this example, the key parameter is set to lambda x: x["age"], which specifies that the sorting should be based on the "age" attribute of each dictionary.

That's it! You now know how to sort a list in Python using both the sorted() function and the sort() method. Additionally, you learned how to sort in descending order and how to sort complex objects by defining a sorting key.