T
Tech Town
Log InSign Up Free
← Back to Blog

June 19, 2025 · admin

Sort Lists


πŸ”€ 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

MethodDescriptionChanges 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=funcSort using custom logicOptional

🏁 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