For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
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!
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:
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:
Also Read: 16+ Essential Python String Methods You Should Know (With Examples) article!
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.
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:
Must Explore: Break Statement in Python: Syntax, Examples, and Common Pitfalls
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:
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:
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:
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!
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:
Also Explore: String split() Method 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.
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:
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:
sorted_values = list(values)
sorted_values.sort()
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:
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:
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
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.
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.
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.
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().
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.
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.
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.
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.
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.
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.
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.
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.
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.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author|900 articles published
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
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.