Lesson explanation
After this lesson, you will be able to:
.sort() and recognize its None return value.sorted() while leaving the original unchanged.reverse=True.Sorting and reversing are different operations. Sorting arranges comparable items by value; reversing just flips their existing order.
items.sort() changes the original list and returns None. If you need a separate ordered version, use sorted(items): it creates a new list, even when the input is another sequence such as a tuple. Both default to ascending order; reverse=True produces descending order.
items.reverse() flips the existing order in place; it does not sort anything. Avoid relying on .sort() or .reverse() to produce a returned list.
This lesson uses values that Python can compare directly (numbers with numbers, or strings with strings). Sorting dictionaries by nested fields with a key= function belongs in Pythonic Thinking, after higher-order functions are introduced.
versions = [5, 2, 4]
versions.sort()
print(versions)Output:
[2, 4, 5]The existing list now holds the sorted values.
latencies = [80, 40, 65]
ordered = sorted(latencies)
print(ordered)
print(latencies)Output:
[40, 65, 80]
[80, 40, 65]sorted() returns a new list, leaving the source unchanged.
scores = [7, 12, 9]
scores.sort(reverse=True)
print(scores)Output:
[12, 9, 7]reverse=True changes the sorting direction.
steps = ["compile", "test", "ship"]
steps.reverse()
print(steps)Output:
['ship', 'test', 'compile']The sequence is flipped, not alphabetically ordered.
| Goal | Python | Modifies original? |
|---|---|---|
| Sort ascending | items.sort() | Yes |
| Sorted copy | sorted(items) | No |
| Sort descending | sorted(items, reverse=True) | No |
| Reverse current order | items.reverse() | Yes |
Result of items.sort() | None | — |
ordered = items.sort() stores None, not a sorted list..reverse() is not equivalent to sorting in descending order..sort() mutates the original list; prefer sorted() when preserving inputs matters.TypeError.