How To Sort Lists in Python Correctly? Understanding sort() and sorted()

Sorting lists is a fundamental task in Python programming, especially when working with numerical data like student grades. Python provides two primary methods for sorting lists: `sort()` and `sorted()`. In this article, we will explore their differences, usage, common mistakes, and best practices.

1. The `sort()` Method: In-Place Sorting.

1.1 Definition and Features.

The `sort()` method is a built-in method for Python lists. It sorts the list in place, meaning it does not create a new list but modifies the existing one. By default, it sorts in ascending order.

1.2 Example.

s1 = [89, 76, 92, 67, 88, 79]
s1.sort()
print(s1) # Output: [67, 76, 79, 88, 89, 92]

This modifies `s1` to be sorted in ascending order.

1.3 Using `reverse=True`.

To sort in descending order, set `reverse=True`:

s1.sort(reverse=True)
print(s1) # Output: [92, 89, 88, 79, 76, 67]

1.4 Common Mistakes.

Some beginners may attempt to use `sort()` incorrectly:

sort(s1) # Error: NameError: name 'sort' is not defined

Since `sort()` is a list method, it must be called as `s1.sort()`, not directly as a function.

Another common mistake:

s2 = s1.sort()
print(s2) # Output: None

Since `sort()` does not return a value, assigning it to another variable results in `None`.

2. The `sorted()` Function: Returning a New List.

2.1 Definition and Features.

Unlike `sort()`, the `sorted()` function returns a new sorted list without modifying the original list.

s2 = sorted(s1)
print(s1) # Original list remains unchanged
print(s2) # Output: Sorted list

2.2 Using `reverse=True`.

To sort in descending order:

s2 = sorted(s1, reverse=True)
print(s2) # Output: [92, 89, 88, 79, 76, 67]

3. Choosing the Right Sorting Method.

  1. Use `sort()` if you want to modify the list directly.
  2. Use `sorted()` if you need to keep the original list unchanged.

4. Conclusion.

This article explained Python’s two list sorting methods, `sort()` and `sorted()`, highlighting their differences and best use cases. By understanding their proper usage, you can avoid common pitfalls and write cleaner, more efficient code.

5. Demo Video.

You can watch the following demo video by select the subtitle to your preferred subtitle language.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top