Python Program to Sort a List
sorted() function or the list's .sort() method, for example: sorted_list = sorted(your_list) or your_list.sort().Examples
How to Think About It
Algorithm
Code
my_list = [3, 1, 2] sorted_list = sorted(my_list) print(sorted_list)
Dry Run
Let's trace sorting the list [3, 1, 2] through the code
Original list
my_list = [3, 1, 2]
Apply sorted()
sorted_list = sorted([3, 1, 2]) results in [1, 2, 3]
Print result
print(sorted_list) outputs [1, 2, 3]
| Step | List State |
|---|---|
| Start | [3, 1, 2] |
| After sorting | [1, 2, 3] |
Why This Works
Step 1: Using sorted()
The sorted() function takes the original list and returns a new list with items in ascending order.
Step 2: Original list unchanged
The original list stays the same because sorted() does not modify it but creates a new sorted list.
Step 3: Printing the sorted list
Printing shows the sorted list, confirming the items are arranged from smallest to largest.
Alternative Approaches
my_list = [3, 1, 2] my_list.sort() print(my_list)
my_list = [3, 1, 2] sorted_list = sorted(my_list, reverse=True) print(sorted_list)
Complexity: O(n log n) time, O(n) space
Time Complexity
Python's built-in sort uses Timsort, which runs in O(n log n) time for average and worst cases, efficiently handling real-world data.
Space Complexity
sorted() creates a new list, so it uses O(n) extra space, while .sort() sorts in place using O(1) extra space.
Which Approach is Fastest?
.sort() is faster when you don't need the original list because it avoids copying, but sorted() is safer if you want to keep the original list unchanged.
| Approach | Time | Space | Best For |
|---|---|---|---|
| sorted() | O(n log n) | O(n) | When you want a new sorted list without changing the original |
| .sort() | O(n log n) | O(1) | When you want to sort the list in place to save memory |
| sorted() with reverse=True | O(n log n) | O(n) | Sorting in descending order while keeping original list |
sorted() when you want a new sorted list and .sort() to change the original list..sort() changes the list in place and returns None, so printing its result shows None.