0
0
PythonProgramBeginner · 2 min read

Python Program to Sort a List

You can sort a list in Python using the sorted() function or the list's .sort() method, for example: sorted_list = sorted(your_list) or your_list.sort().
📋

Examples

Input[3, 1, 2]
Output[1, 2, 3]
Input[10, -1, 5, 0]
Output[-1, 0, 5, 10]
Input[]
Output[]
🧠

How to Think About It

To sort a list, think about arranging the items from smallest to largest. Python provides easy ways to do this by comparing each item and placing them in order automatically.
📐

Algorithm

1
Get the list you want to sort.
2
Use a sorting method to arrange the items in ascending order.
3
Return or print the sorted list.
💻

Code

python
my_list = [3, 1, 2]
sorted_list = sorted(my_list)
print(sorted_list)
Output
[1, 2, 3]
🔍

Dry Run

Let's trace sorting the list [3, 1, 2] through the code

1

Original list

my_list = [3, 1, 2]

2

Apply sorted()

sorted_list = sorted([3, 1, 2]) results in [1, 2, 3]

3

Print result

print(sorted_list) outputs [1, 2, 3]

StepList 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

Using list.sort() method
python
my_list = [3, 1, 2]
my_list.sort()
print(my_list)
This method sorts the list in place and changes the original list.
Sorting in descending order
python
my_list = [3, 1, 2]
sorted_list = sorted(my_list, reverse=True)
print(sorted_list)
This sorts the list from largest to smallest using the reverse=True option.

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.

ApproachTimeSpaceBest 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=TrueO(n log n)O(n)Sorting in descending order while keeping original list
💡
Use sorted() when you want a new sorted list and .sort() to change the original list.
⚠️
Forgetting that .sort() changes the list in place and returns None, so printing its result shows None.