Sort in Python: Everything You Need to Know About It- 2026
Whether you’re a beginner just starting your Python journey or someone looking to brush up on fundamentals, understanding how to sort in Python is absolutely essential. Sorting is one of those operations you’ll use constantly—whether you’re organizing data for analysis, preparing user inputs, or simply making your output more readable.
Table Of Content
- What Is Sorting in Python?
- Understanding list.sort() in Python
- How Does It Work?
- Syntax
- Example
- Sorting in Descending Order with list.sort()
- Syntax
- Example
- What Is sorted() in Python?
- Key Points About sorted()
- Syntax
- Example
- The Key Differences Between sort() and sorted()
- When to Use Which?
- Parameters for Sorting in Python
- 1. The Reverse Parameter
- 2. The Key Parameter
- Operator Module Functions for Sorting
- a) itemgetter
- b) attrgetter
- c) methodcaller
- Ascending and Descending Sort in Python
- Example 1: Ascending Order
- Example 2: Descending Order
- Sort Stability and Complex Sorts
- What Is a Stable Sort?
- Complex Sorts: Multiple Sorting Criteria
- Practical Tips for Sorting in Python
- Conclusion
- Frequently Asked Questions (FAQs)
- 1. What is the difference between sort() and sorted() in Python?
- 2. How do I sort a list in descending order in Python?
- 3. Can I sort a list of dictionaries in Python?
- 4. Is Python’s sort stable?
- 5. How do I sort strings case-insensitively in Python?
In this comprehensive guide, we’ll break down everything you need to know about sorting in Python. We’ll cover built-in functions, practical examples, key differences, and even some advanced techniques.
What Is Sorting in Python?
Before we get into the nitty-gritty details, let’s start with the basics.
Sorting, in simple terms, means arranging data in a specific order—either ascending (smallest to largest) or descending (largest to smallest). Think of it like organizing your bookshelf alphabetically or arranging your playlist by song duration.
In Python, you don’t need to write complex algorithms from scratch. The language provides powerful built-in functions that make sorting incredibly easy and efficient. Whether you’re working with numbers, strings, or even custom objects, Python has got you covered.
Understanding list.sort() in Python
The list.sort() method is one of the most straightforward ways to sort in Python. It’s a built-in function specifically designed for lists, and it modifies the original list directly.
How Does It Work?
When you call list.sort(), Python rearranges the elements in your list in ascending order by default. The original list gets updated, and no new list is created.
Syntax
Pythonlist_name.sort()
Example
Pythonnumbers = [64, 34, 25, 12, 22, 11, 90]
numbers.sort()
print(numbers)
Output:
text[11, 12, 22, 25, 34, 64, 90]
See how simple that was? The list is now sorted in ascending order, and the original numbers list has been modified.
Sorting in Descending Order with list.sort()
What if you need your data in reverse order? No problem! The list.sort() method accepts an optional parameter called reverse.
Syntax
Pythonlist_name.sort(reverse=True)
Example
Pythonnumbers = [64, 34, 25, 12, 22, 11, 90]
numbers.sort(reverse=True)
print(numbers)
Output:
text[90, 64, 34, 25, 22, 12, 11]
Now your list is sorted from largest to smallest. Pretty neat, right?
What Is sorted() in Python?
While list.sort() modifies the original list, the sorted() function takes a different approach. It creates a new sorted list and leaves the original list untouched.
Key Points About sorted()

- Returns a new list (doesn’t modify the original)
- Works with any iterable (lists, tuples, strings, etc.)
- The return type is always a list
Syntax
Pythonnew_list = sorted(old_list)
Example
Pythonnumbers = [64, 34, 25, 12, 22, 11, 90]
sorted_numbers = sorted(numbers)
print("Original:", numbers)
print("Sorted:", sorted_numbers)
Output:
textOriginal: [64, 34, 25, 12, 22, 11, 90]
Sorted: [11, 12, 22, 25, 34, 64, 90]
Notice how the original numbers list remains unchanged? That’s the beauty of sorted().
The Key Differences Between sort() and sorted()
This is a question that often confuses beginners. Let’s clear it up with a simple comparison:
| Feature | sort() | sorted() |
|---|---|---|
| Modifies Original | Yes (in-place) | No (creates new list) |
| Return Type | None | List |
| Speed | Faster | Slightly slower |
| Memory Usage | Less (no copy) | More (creates copy) |
| Works On | Lists only | Any iterable |
When to Use Which?
- Use
list.sort()when you want to modify the original list and don’t need to keep the original order - Use
sorted()when you need to preserve the original list or when working with non-list iterables
Parameters for Sorting in Python
Both sort() and <a href="https://www.kaashivinfotech.com/blog/python-list-sorting-guide/">sorted()</a> support optional parameters that give you more control over how your data gets sorted. Let’s explore them.
1. The Reverse Parameter
As we’ve already seen, the reverse parameter controls the sorting order:
reverse=False(default): Ascending orderreverse=True: Descending order
Example with reverse=False:
Pythonfruits = ['banana', 'apple', 'cherry', 'date']
fruits.sort(reverse=False)
print(fruits)
Output:
text['apple', 'banana', 'cherry', 'date']
2. The Key Parameter
The key parameter is where things get really interesting. It allows you to specify a custom function that determines how elements should be compared during sorting.
Example: Sorting by String Length
Pythonwords = ['python', 'is', 'awesome', 'and', 'fun']
words.sort(key=len)
print(words)
Output:
text['is', 'and', 'fun', 'python', 'awesome']
The list is now sorted by the length of each word instead of alphabetically!
Operator Module Functions for Sorting
Python’s operator module provides some handy functions that make sorting even more powerful. Here are the three main ones:
a) itemgetter
Useful for sorting lists of tuples or dictionaries by specific indices or keys.
Example:
Pythonfrom operator import itemgetter
students = [('John', 85), ('Alice', 92), ('Bob', 78)]
students.sort(key=itemgetter(1))
print(students)
Output:
text[('Bob', 78), ('John', 85), ('Alice', 92)]
The list is sorted by the second element (the scores) in each tuple.
b) attrgetter
Perfect for sorting objects by their attributes.
Example:
Pythonfrom operator import attrgetter
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
students = [Student('John', 85), Student('Alice', 92), Student('Bob', 78)]
students.sort(key=attrgetter('grade'))
for student in students:
print(student.name, student.grade)
Output:
textBob 78
John 85
Alice 92
c) methodcaller
Allows you to sort by calling a method on each element.
Example:
Pythonfrom operator import methodcaller
words = ['Python', 'java', 'C++', 'JavaScript']
words.sort(key=methodcaller('lower'))
print(words)
Output:
text['C++', 'java', 'JavaScript', 'Python']
The sorting is case-insensitive because we’re using the lower() method.
Ascending and Descending Sort in Python
Let’s put everything together with some practical examples using the sorted() function.
Example 1: Ascending Order
Pythonnumbers = [5, 2, 9, 1, 5, 6]
result = sorted(numbers)
print(result)
Output:
text[1, 2, 5, 5, 6, 9]
Example 2: Descending Order
Pythonnumbers = [5, 2, 9, 1, 5, 6]
result = sorted(numbers, reverse=True)
print(result)
Output:
text[9, 6, 5, 5, 2, 1]
Pro Tip: Python’s sorting is stable, which means that when multiple elements have the same value, their original order is preserved. This is incredibly useful for complex sorting operations!
Sort Stability and Complex Sorts
What Is a Stable Sort?
A stable sort maintains the relative order of elements that compare equal. Python has guaranteed stable sorting since version 2.2.
Example:
Pythonfrom operator import itemgetter
restaurant_data = [('vegetarian', 1), ('eggetarian', 2), ('vegetarian', 2)]
print(sorted(restaurant_data, key=itemgetter(0)))
Output:
text[('vegetarian', 1), ('vegetarian', 2), ('eggetarian', 2)]
Notice how both ‘vegetarian’ entries kept their original order? That’s stability in action!
Complex Sorts: Multiple Sorting Criteria
Sometimes you need to sort by multiple criteria. Python makes this elegant with the ability to chain sorts.
Example: Sort by Grade (Ascending), Then by Age (Descending)
Pythonstudents = [
{'name': 'Alice', 'age': 25, 'grade': 85},
{'name': 'Bob', 'age': 22, 'grade': 90},
{'name': 'Charlie', 'age': 25, 'grade': 85}
]
# First sort by age (descending), then by grade (ascending)
students.sort(key=lambda x: x['age'], reverse=True)
students.sort(key=lambda x: x['grade'])
for student in students:
print(student)
Output:
text{'name': 'Alice', 'age': 25, 'grade': 85}
{'name': 'Charlie', 'age': 25, 'grade': 85}
{'name': 'Bob', 'age': 22, 'grade': 90}
The stability of Python’s sort ensures that when grades are equal, the age ordering from the first sort is preserved.
Practical Tips for Sorting in Python
Here are some quick tips to keep in mind:
- Default behavior: Both
sort()andsorted()sort in ascending order by default - Performance:
list.sort()is generally faster since it doesn’t create a copy - Memory: Use
sorted()when you need to keep the original list - Custom sorting: The
keyparameter is your best friend for complex sorting needs - Stability: Python’s stable sort is perfect for multi-level sorting operations
Conclusion
Mastering how to sort in Python is a fundamental skill that will serve you well throughout your programming career. In this guide, we’ve covered:
- The basics of sorting in Python
- How to use
list.sort()for in-place sorting - How to use
sorted()to create new sorted lists - The key differences between
sort()andsorted() - The
reverseandkeyparameters for custom sorting - Operator module functions (
itemgetter,attrgetter,methodcaller) - Ascending and descending sort examples
- Sort stability and complex multi-level sorting
Whether you’re working with simple lists of numbers or complex data structures, Python’s sorting capabilities are powerful, flexible, and easy to use. The key is to practice with different examples and experiment with the various parameters we’ve discussed.
Ready to take your Python skills to the next level? Explore our comprehensive Python training programs at Kaashiv Infotech and master not just sorting, but all the essential Python concepts you need for a successful career in programming and data science.
Frequently Asked Questions (FAQs)
1. What is the difference between sort() and sorted() in Python?
The main difference is that list.sort() modifies the original list in-place and returns None, while sorted() creates a new sorted list and leaves the original unchanged. Use sort() when you don’t need the original order, and sorted() when you want to preserve it.
2. How do I sort a list in descending order in Python?
You can sort in descending order by using the reverse=True parameter with either list.sort(reverse=True) or sorted(list, reverse=True). For example: numbers.sort(reverse=True) will sort your list from largest to smallest.
3. Can I sort a list of dictionaries in Python?
Yes! You can sort a list of dictionaries using the key parameter. For example: sorted(dict_list, key=lambda x: x['key_name']) will sort the list based on the specified dictionary key.
4. Is Python’s sort stable?
Yes, Python’s sorting algorithm is stable since version 2.2. This means that when multiple elements have the same key value, their original relative order is preserved in the sorted output.
5. How do I sort strings case-insensitively in Python?
Use the key parameter with str.lower or str.casefold. For example: sorted(string_list, key=str.lower) will sort strings without considering case differences.

