🔤 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