View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

How to Use Sort in Python: Methods, Parameters, and Examples

Updated on 29/05/20255,798 Views

Sorting is a fundamental operation in Python that helps you arrange data in a specific order - either ascending or descending. The built-in sort() method in Python is especially useful when working with lists. Whether you are organizing numbers, strings, or custom objects, learning how to use sort in Python efficiently can simplify many coding tasks.

In this article, we’ll explore the sort() method in Python with real-world examples and explain how it works at different levels - from basic to advanced. You will learn the syntax of sort in Python, how to sort in descending order, apply custom sorting using the key parameter, perform case-insensitive sorts, and more. We will also cover common mistakes to avoid and the ideal scenarios where you should use the sort() method over other techniques.

Pursue our Software Engineering courses to get hands-on experience!

What is sort() in Python?

The sort() method in Python is used to arrange elements of a list in a particular order. By default, it sorts the list in ascending order. This method is available only for lists and directly updates the original list - it doesn’t create a new one.

You can use it to sort numerical data, strings, or even custom objects based on specific rules. It is especially helpful when you need a clean, ordered dataset for processing or presentation.

Take your skills to the next level with these top programs:

Syntax of sort() Method in Python

The sort() method in Python is used to arrange the elements of a list in a defined order. You can sort items in ascending or descending order, or even apply custom sorting logic. Python allows you to control the sorting behavior using two optional parameters: key and reverse.

Here is the syntax of the sort() method:

list.sort(key=None, reverse=False)

Let’s break it down and see how each part works through an example.

Example: Using sort() with key and reverse Parameters

# Define a list of tuples where each tuple contains (name, age)
people = [("Anil", 25), ("Vikram", 30), ("Rishabh", 20)]

# Sort the list by age using the 'key' parameter
people.sort(key=lambda person: person[1]) # Sort by the second item (age)

# Print the sorted list
print("Sorted by age (ascending):", people)

# Now sort in descending order using 'reverse=True'
people.sort(key=lambda person: person[1], reverse=True)

# Print the sorted list again
print("Sorted by age (descending):", people)

Output:

Sorted by age (ascending): [('Rishabh', 20), ('Anil', 25), ('Vikram', 30)]

Sorted by age (descending): [('Vikram', 30), ('Anil', 25), ('Rishabh', 20)]

Explanation:

  • key=lambda person: person[1]:
    • This tells Python to sort the list based on the second element (index 1) of each tuple, which is the age.
    • The key function doesn’t change the data; it only guides the sorting process.
  • reverse=False:
    • By default, this is set to False, so the list is sorted in ascending order.
  • reverse=True:
    • When this is set to True, the list is sorted in descending order.
  • The sort() method modifies the original list, so no new list is returned.

Also Read: 16+ Essential Python String Methods You Should Know (With Examples) article!

sort in Python Examples

Let’s now explore how the sort() method in Python works through real-world examples. We will start with basic usage and gradually move to intermediate and advanced sorting techniques.

Basic Level – Sorting List in Descending Order

The sort() method sorts data in ascending order by default. To sort in descending order, we need to use the reverse=True parameter.

# Define a list of numbers
numbers = [10, 4, 15, 2, 33]

# Sort the list in descending order
numbers.sort(reverse=True)

# Print the sorted list
print("Descending Order:", numbers)

Output:

Descending Order: [33, 15, 10, 4, 2]

Explanation:

  • The list numbers contain integers in random order.
  • We use reverse=True with sort() to arrange the numbers from highest to lowest.
  • The original list gets updated directly - no new list is returned.
  • This method is useful when ranking values from top to bottom.

Must Explore: Break Statement in Python: Syntax, Examples, and Common Pitfalls

Intermediate Level – Case Insensitive Sort

When sorting strings, uppercase letters come before lowercase by default. To ignore the case while sorting, use key=str.lower.

# Define a list of mixed-case words
words = ["banana", "Apple", "cherry", "apple", "Banana"]

# Sort the list in a case-insensitive manner
words.sort(key=str.lower)

# Print the sorted list
print("Case Insensitive Sort:", words)

Output:

Case Insensitive Sort: ['Apple', 'apple', 'banana', 'Banana', 'cherry']

Explanation:

  • The list of words includes both uppercase and lowercase strings.
  • By using key=str.lower, we tell Python to compare all strings in lowercase internally.
  • This method avoids unexpected results due to case sensitivity.
  • It’s especially useful when sorting names, titles, or any text-based data.

Advanced Level – Custom Sorting Using key Parameter

Sometimes, we want to sort data based on specific criteria. The key parameter helps us define that custom logic.

Example 1: Sort List of Tuples by Second Value

# List of tuples where each tuple is (name, age)
people = [("Harsh", 30), ("Tanu", 22), ("Anil", 25)]

# Sort the list by age (second element of each tuple)
people.sort(key=lambda person: person[1])

# Print the sorted list
print("Sorted by Age:", people)

Output:

Sorted by Age: [('Tanu', 22), ('Anil', 25), ('Harsh', 30)]

Explanation:

  • Each tuple has two elements: name and age.
  • The lambda function lambda person: person[1] tells Python to sort by the second element (age).
  • This is useful when sorting complex data structures like database rows or student records.

Example 2: Sorting with a Custom Function

You can also define your own function and use it as the key.

# Define a list of numbers
nums = [3, -7, 2, -1, 5]

# Define a custom function that returns the absolute value
def absolute_value(n):
return abs(n)

# Sort the list based on absolute values
nums.sort(key=absolute_value)

# Print the sorted list
print("Sorted by Absolute Value:", nums)

Output:

Sorted by Absolute Value: [-1, 2, 3, 5, -7]

Explanation:

  • We created a function absolute_value() that returns the absolute value of a number.
  • We passed this function to the key parameter to sort numbers based on their absolute values.
  • This approach helps in scenarios where the sorting logic needs more control.

These examples show how flexible and powerful the sort() method in Python can be. Whether you're working with simple lists or complex data, understanding how to use key and reverse lets you sort effectively in any scenario.

Must Read: Python Keywords and Identifiers article!

When Should You Use the sort() Method in Python?

The sort() method is ideal when you want to arrange elements of a list directly without creating a new list. It works best when you need an in-place sort that updates the original list. This saves memory and makes your code more efficient.

You should use sort in Python when:

  • Working with lists only (as sort() is not available for other data types).
  • Don’t need to keep the original order of the list.
  • Want to apply custom sorting logic using the key parameter.
  • Want to sort data in ascending or descending order directly.

Also Explore: String split() Method in Python

Common Errors While Using sort() in Python

While the sort() method in Python is powerful, developers often encounter common mistakes. These usually happen when sorting mixed data types, applying incorrect functions, or misunderstanding how the key parameter works.

Error 1: Sorting Lists with Mixed Data Types

Python does not allow sorting of lists containing incompatible data types like integers and strings.

# A list with mixed types
data = [5, "Anil", 10, "Kunal"]

# Trying to sort this list will raise an error
data.sort()

Output:

ERROR!

Traceback (most recent call last):

  File "<main.py>", line 5, in <module>

TypeError: '<' not supported between instances of 'str' and 'int'

Explanation: 

  • Python cannot compare numbers (int) and strings (str) directly.
  • The sort() method fails when elements don’t share a common type.
  • To fix this, make sure all items in the list are of the same data type.

Error 2: Using sort() on Non-List Types

The sort() method is only available for lists. Trying it on other data types like tuples or dictionaries will fail.

# A tuple instead of a list
values = (3, 1, 2)

# Attempting to sort it like a list
values.sort()

Output:

ERROR!

Traceback (most recent call last):

  File "<main.py>", line 5, in <module>

AttributeError: 'tuple' object has no attribute 'sort'

Explanation: 

  • Tuples are immutable and do not support the sort() method.
  • You should first convert the tuple into a list using list() before sorting:
sorted_values = list(values)
sorted_values.sort()

Error 3: Forgetting to Use key= When Needed

If you want custom sorting and don’t specify the key parameter, results may not behave as expected.

# List of tuples
records = [("Pizza", 2), ("Biryani", 1), ("Burger", 3)]

# Incorrectly trying to sort by the second value
records.sort(lambda item: item[1]) # Missing 'key='

Output:

ERROR!

Traceback (most recent call last):

  File "<main.py>", line 5, in <module>

TypeError: sort() takes no positional arguments

Explanation: 

  • The sort() method accepts the sorting function only as a keyword argument.
  • You must write key=lambda item: item[1] instead of just passing the function.

Error 4: Expecting a Return Value from sort()

Some users mistakenly assign the result of sort() to a variable. But sort() returns None.

# List of numbers
nums = [4, 1, 3]

# Incorrect assignment
result = nums.sort()

print(result)

Output:

None

Explanation: 

  • The sort() method works in-place and modifies the list directly.
  • It returns None, not a new sorted list.
  • If you need a new sorted list, use sorted(nums) instead.

By avoiding these common mistakes, you can use the sort() method in Python more effectively. Always ensure the list contains compatible data types and use parameters like key and reverse properly.

Must Explore: Self in Python

sort() vs sorted() in Python

Both sort() and sorted() are used to arrange elements in order. However, they differ in how they operate and what they return. Understanding their differences will help you choose the right method for your task.

Here’s a comparison between the two:

Feature

sort() Method

sorted() Function

Works On

Lists only

Any iterable (lists, tuples, dicts)

Return Type

Returns None

Returns a new sorted list

In-place Modification

Yes (modifies original list)

No (original stays unchanged)

Used With

list.sort()

sorted(iterable)

Memory Efficient

Yes

No (creates a copy)

Supports key and reverse

Yes

Yes

Common Use Case

When list needs to be updated in-place

When original data must remain intact

The main difference between sort() and sorted() in Python is that the sort() method modifies the original list. Meanwhile, the sorted() function returns a new list. Use the sort() method when you want an in-place sort for lists and don’t need the original data. Use the sorted() function when you want to keep the original data intact and need a new sorted result.

Conclusion

The sort() method in Python is a simple yet powerful tool to organize data in ascending or descending order. It works directly on lists, modifying them in-place. This makes it efficient when memory usage is a concern.

FAQs

1. Can you sort a dictionary using the sort() method in Python?

No, you cannot directly use the sort() method on a dictionary since it is not a list. However, you can sort dictionary keys or values by converting them into a list and using the sorted() function for that purpose.

2. What happens if you try to sort a set in Python using sort()?

The sort() method works only on lists. If you try to use it on a set, you will get an AttributeError. To sort a set, first convert it into a list using list(set_name) and then apply sort().

3. Is it possible to sort a list of dictionaries using the sort() method in Python?

Yes, you can sort a list of dictionaries using the sort() method by passing a key parameter. The key should be a lambda function that returns the dictionary field by which you want to sort.

4. How do you sort a list of tuples based on the second element?

To sort a list of tuples by the second element, use the key argument. Pass a lambda function like lambda x: x[1]. This tells Python to sort the list based on the value at index 1 in each tuple.

5. What is the difference between using reverse=True and key=lambda in sort()?

The reverse=True argument simply changes the order from ascending to descending. In contrast, key=lambda customizes the sorting logic itself, like sorting by string length or a specific tuple index.

6. Does sort() work with None values in a list?

No, Python does not allow comparisons between NoneType and other data types like integers or strings. If your list contains None, trying to sort it will raise a TypeError. Always clean such values beforehand.

7. How does Python handle sorting of Unicode or accented characters?

By default, Python sorts Unicode characters based on their Unicode code points. This may lead to unexpected results with accented characters. For locale-aware sorting, use the locale module to get culturally correct orderings.

8. Can sort() in Python handle nested lists or multidimensional lists?

The sort() method can handle nested lists, but only if each sublist is comparable. You can also sort based on elements inside sublists using a key function like lambda x: x[1] for sorting by inner values.

9. Is sort in Python case-sensitive by default?

Yes, sort() is case-sensitive. Uppercase letters come before lowercase ones in ASCII. To perform a case-insensitive sort, use the key=str.lower argument, which forces all strings to be compared in lowercase.

10. What is the best way to sort a list in descending alphabetical order?

You can sort a list in descending alphabetical order using sort(reverse=True). If the sort should ignore case, combine it with key=str.lower. This makes the sorting both reverse and case-insensitive.

11. When should I prefer sorted() over sort() in Python?

You should use sorted() when you need a new sorted list while preserving the original. It’s especially useful in situations like data analysis or logging, where keeping the original order unchanged is important.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Pavan Vadapalli

Author|900 articles published

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology s....

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.