In this Python tutorial, you will learn how to sort a list in ascending or descending order using the sorted() built-in function. You will also learn how sorted() differs from list.sort() and how to sort values using a custom key.
Sort a Python List using sorted()
The sorted() function accepts an iterable and returns a new list containing its elements in sorted order. When you pass a list to sorted(), the original list remains unchanged.
sorted(iterable, key=None, reverse=False)
iterableis the list or other iterable to sort.keyis an optional function used to obtain the value that controls the sort order.reverseis an optional Boolean value. Its default value isFalse. Set it toTruefor descending order.
Python sorts numbers from smallest to largest and strings in lexicographical order by default.
Python sorted() and the Original List
The return value of sorted() is a new list. This is useful when you need both the original order and a sorted version of the same data.
numbers = [8, 3, 6, 1]
ordered_numbers = sorted(numbers)
print(numbers)
print(ordered_numbers)
Output
[8, 3, 6, 1]
[1, 3, 6, 8]
Python Programs to Sort a List with sorted()
1. Sort a Python List in Ascending Order
In the following program, we take a list of integers and sort them in ascending order using the sorted() function.
Pass the list as the argument to sorted() without specifying reverse. The default value reverse=False sorts the elements from smallest to largest.
main.py
#initialize list
nums = [21, 28, 14, 96, 84, 65, 74, 31]
#sort list
sortedList = sorted(nums)
#print sorted list
print(sortedList)
Output
[14, 21, 28, 31, 65, 74, 84, 96]
The returned list contains the same values as nums, arranged in ascending order.
Reference tutorials for sorting the integer list
2. Sort a Python List in Descending Order
In the following program, we take a list of integers and sort them in descending order using the sorted() function.
To make sorted() arrange the elements from largest to smallest, pass reverse=True.
main.py
#initialize list
nums = [21, 28, 14, 96, 84, 65, 74, 31]
#sort list
sortedList = sorted(nums, reverse=True)
#print sorted list
print(sortedList)
Output
[96, 84, 74, 65, 31, 28, 21, 14]
The reverse=True argument changes only the direction of the result. It does not modify the original list.
Reference tutorials for descending list sorting
3. Sort a List of Strings Alphabetically
You can pass a list of strings to sorted(). By default, Python compares strings lexicographically and uppercase letters are ordered before lowercase letters.
names = ["Ravi", "Anita", "Kiran", "Bala"]
sorted_names = sorted(names)
print(sorted_names)
Output
['Anita', 'Bala', 'Kiran', 'Ravi']
4. Sort Strings without Case-Sensitive Ordering
To sort strings without uppercase and lowercase differences affecting their positions, pass str.lower as the key argument.
words = ["banana", "Apple", "cherry", "apricot"]
sorted_words = sorted(words, key=str.lower)
print(sorted_words)
Output
['Apple', 'apricot', 'banana', 'cherry']
The key function is used for comparison. The original strings are preserved in the returned list.
5. Sort a List by String Length
Pass len as the key argument to arrange strings according to their number of characters.
languages = ["Python", "C", "JavaScript", "Go"]
by_length = sorted(languages, key=len)
print(by_length)
Output
['C', 'Go', 'Python', 'JavaScript']
6. Sort a List of Tuples by a Specific Item
For structured values such as tuples, use a key function to select the item that should control the sorting. The following example sorts student records by score.
students = [("Asha", 82), ("Manoj", 74), ("Divya", 91)]
sorted_students = sorted(students, key=lambda student: student[1])
print(sorted_students)
Output
[('Manoj', 74), ('Asha', 82), ('Divya', 91)]
The lambda function returns the second item from each tuple, so the scores determine the order.
Difference Between sorted() and list.sort()
Both sorted() and list.sort() can arrange list elements, but they behave differently.
| Feature | sorted() | list.sort() |
|---|---|---|
| Return value | Returns a new sorted list | Returns None |
| Original list | Remains unchanged | Is modified in place |
| Accepted input | Accepts any iterable | Works only on lists |
key and reverse | Supported | Supported |
Use sorted() when you need a separate sorted result or when the input is not a list. Use list.sort() when modifying the existing list is acceptable.
Errors and Edge Cases When Sorting Python Lists
Sorting an Empty List
Sorting an empty list is valid. The result is another empty list.
values = []
print(sorted(values))
Output
[]
Sorting Mixed Incompatible Types
In Python 3, values of unrelated types such as integers and strings generally cannot be directly ordered. Calling sorted() on such a list raises a TypeError.
values = [10, "20", 5]
sorted_values = sorted(values)
Convert the values to a common comparable form or provide an appropriate key function before sorting.
Frequently Asked Questions about Python sorted()
Does sorted() modify the original Python list?
No. sorted() creates and returns a new list. The original list keeps its existing order.
How do I sort a Python list from largest to smallest?
Pass reverse=True to sorted(), as in sorted(numbers, reverse=True).
How do I sort a list using one property of each item?
Pass a function to the key parameter. Python calls that function for each item and uses the returned value for comparisons.
Can sorted() sort tuples, sets, and dictionaries?
Yes. sorted() accepts any iterable and always returns a list. For a dictionary, iterating directly over it sorts its keys unless you explicitly pass its values or items.
Python List Sorting Summary
Use sorted(list) for ascending order and sorted(list, reverse=True) for descending order. Use the key parameter when the sort should be based on a derived value such as lowercase text, string length, or one field in a tuple. Unlike list.sort(), the sorted() function returns a new list without changing the original.
In this Python Tutorial, we learned how to sort a list in Python using the sorted() built-in function in ascending or descending order and how to apply custom sorting rules.
TutorialKart.com