I want to share something that’s as simple as it is essential: sorting a list in Python. Whether you’re just starting out with Python or need a quick refresher, this is for you.
So, picture this: you’ve got a list of numbers and need to sort them. Here’s the list:
nums = [56, 1, 45, 9, 865, 34]
How do you sort it? Python makes this ridiculously easy. Just use the sort()
method:
nums.sort()
print(nums)
And boom! Your list is now sorted in ascending order:
[1, 9, 34, 45, 56, 865]
A Few Things to Know About sort()
It’s In-Place: The sort()
method modifies the original list. This means that after calling nums.sort()
, the nums
list itself is changed. If you need to keep the original list intact, you’ll want a different approach (more on that in a sec).
Descending Order? No Problem! Want the biggest numbers first? Just pass reverse=True
to sort()
:
nums.sort(reverse=True)
print(nums)
[865, 56, 45, 34, 9, 1]
It’s Fast: Python’s sort is implemented using Timsort, which is super efficient for most use cases. You’re in good hands.
What If You Want to Keep the Original List?
If you don’t want to mess with the original list, Python’s sorted()
function is your friend. Here’s how it works:
nums = [56, 1, 45, 9, 865, 34]
sorted_nums = sorted(nums)
print(sorted_nums) # [1, 9, 34, 45, 56, 865]
print(nums) # [56, 1, 45, 9, 865, 34]
See? The nums
list stays untouched, and sorted_nums
gives you the sorted version.
You can also use sorted()
for descending order with the same reverse=True
argument:
sorted_nums_desc = sorted(nums, reverse=True)
print(sorted_nums_desc) # [865, 56, 45, 34, 9, 1]
Which One Should You Use?
If you need to sort a list and don’t care about keeping the original, go for sort()
. It’s straightforward and does the job. But if you’re working in a situation where the original list needs to stay as-is (maybe for debugging or comparisons), then sorted()
is the way to go.
Wrapping It Up
Sorting in Python is one of those little things that’s so simple it feels like magic. Just a quick call to sort()
or sorted()
, and you’re done. No need to reinvent the wheel or write custom sorting algorithms – Python’s got you covered.