π€ How to Sort a List in Python β Master sort() and sorted() | TechTown.in
Sorting a list is a fundamental task in Python, whether you’re arranging names alphabetically, scores in descending order, or filtering product prices. Python gives you powerful tools to sort lists easily β both in-place and by returning a new sorted copy.
In this tutorial, weβll explore how to sort Python lists using sort(), sorted(), custom key functions, and how to sort in reverse order.
πΉ 1. Use sort() to Sort a List (In-Place)
The simplest way to sort a list is by using the sort() method. It modifies the original list.
Example:
fruits = ["banana", "apple", "cherry"]
fruits.sort()
print(fruits) # ['apple', 'banana', 'cherry']
β The list is now sorted in ascending (alphabetical) order.
π 2. Sort in Reverse Order
You can sort the list in descending order using reverse=True.
numbers = [100, 50, 25, 75]
numbers.sort(reverse=True)
print(numbers) # [100, 75, 50, 25]
π¦ 3. Use sorted() to Keep Original List Untouched
Unlike sort(), the sorted() function returns a new list, keeping the original unchanged.
names = ["John", "Alice", "Bob"]
sorted_names = sorted(names)
print(sorted_names) # ['Alice', 'Bob', 'John']
print(names) # ['John', 'Alice', 'Bob']
β Great when you want to keep the original list intact.
π§ 4. Sort with Custom Key Functions
Use the key= parameter to define custom sorting logic.
Sort by Length:
words = ["banana", "kiwi", "apple"]
words.sort(key=len)
print(words) # ['kiwi', 'apple', 'banana']
Sort by Last Letter:
words.sort(key=lambda x: x[-1])
print(words)
π’ 5. Sort a List of Numbers
Python sorts integers and floats just like strings:
scores = [70, 90, 50, 100]
scores.sort()
print(scores) # [50, 70, 90, 100]
π« Mixed Data Types Canβt Be Sorted
You canβt sort a list with incompatible types:
items = ["apple", 10, True]
items.sort() # β TypeError
β Keep list items uniform in type for sorting.
π§ͺ Real-World Example β Sorting a Dictionary by Value
Sort list of tuples or dictionary items:
products = [("pen", 10), ("notebook", 50), ("eraser", 5)]
products.sort(key=lambda x: x[1])
print(products) # [('eraser', 5), ('pen', 10), ('notebook', 50)]
π§ Summary β Sorting in Python
| Method | Description | Changes Original? |
|---|---|---|
list.sort() | Sorts the list in-place | β Yes |
list.sort(reverse=True) | Sort in descending order | β Yes |
sorted(list) | Returns a new sorted list | β No |
key=func | Sort using custom logic | Optional |
π Final Thoughts
Sorting is a critical skill in Python, used in everything from reports to leaderboards. With just a few lines of code, you can organize your data your way using sort() or sorted() β and even apply your own logic with custom key functions.
π Learn more about Python Lists at TechTown.in