Last modified: Mar 25, 2026 By Alexander Williams
Python Sort Array: Methods & Examples
Sorting data is a core programming task. In Python, you often work with lists, which serve as arrays. Knowing how to sort them is essential.
Python provides powerful, built-in tools for sorting. You can sort in-place or get a new sorted list. This guide covers all the key methods.
Understanding Python Arrays and Lists
Python does not have a native array data type like other languages. Instead, it uses lists. Lists are ordered, mutable collections.
They can hold items of different data types. For most sorting purposes, a Python list is your "array". Knowing the Python Array Length: How to Find It is also crucial for managing your data.
The sort() Method: In-Place Sorting
The list.sort() method modifies the original list. It arranges the elements in ascending order by default. No new list is created.
This is efficient for memory. Use it when you don't need the original order.
# Example of the sort() method
numbers = [5, 2, 9, 1, 5, 6]
print("Original list:", numbers)
numbers.sort() # Sorts the list in-place
print("Sorted list:", numbers)
Original list: [5, 2, 9, 1, 5, 6]
Sorted list: [1, 2, 5, 5, 6, 9]
The sorted() Function: Creating a New Sorted List
The sorted() function takes an iterable and returns a new sorted list. The original data remains unchanged.
This is useful when you need to preserve the original sequence. It works on any iterable, like tuples or strings.
# Example of the sorted() function
original_numbers = [3, 1, 4, 1, 5]
print("Original:", original_numbers)
new_sorted_list = sorted(original_numbers) # Returns a new list
print("New sorted list:", new_sorted_list)
print("Original is unchanged:", original_numbers)
Original: [3, 1, 4, 1, 5]
New sorted list: [1, 1, 3, 4, 5]
Original is unchanged: [3, 1, 4, 1, 5]
Sorting in Reverse Order
Both sort() and sorted() accept a reverse parameter. Set it to True for descending order.
# Sorting in reverse (descending) order
numbers = [5, 2, 9, 1]
numbers.sort(reverse=True)
print("sort() with reverse=True:", numbers)
new_list = sorted([5, 2, 9, 1], reverse=True)
print("sorted() with reverse=True:", new_list)
sort() with reverse=True: [9, 5, 2, 1]
sorted() with reverse=True: [9, 5, 2, 1]
Custom Sorting with the key Parameter
The key parameter is powerful. It lets you define a function that returns a value for sorting. The list is sorted based on these computed keys.
For example, you can sort strings by length or sort objects by an attribute.
# Sorting by string length using the key parameter
fruits = ["apple", "kiwi", "banana", "fig"]
# Sort by the length of each string
fruits.sort(key=len)
print("Sorted by length:", fruits)
# Using sorted() with a custom key
numbers_as_strings = ["10", "2", "1", "20"]
# Sort by numeric value, not lexicographically
sorted_numbers = sorted(numbers_as_strings, key=int)
print("Sorted by integer value:", sorted_numbers)
Sorted by length: ['fig', 'kiwi', 'apple', 'banana']
Sorted by integer value: ['1', '2', '10', '20']
Sorting Complex Data Structures
You often need to sort lists of dictionaries or tuples. The key parameter with a lambda function is perfect for this.
A lambda is a small, anonymous function defined in a single line.
# Sorting a list of dictionaries
students = [
{"name": "Alice", "grade": 85},
{"name": "Bob", "grade": 92},
{"name": "Charlie", "grade": 78}
]
# Sort the list of dicts by the 'grade' key
students_sorted_by_grade = sorted(students, key=lambda student: student["grade"])
print("Sorted by grade:", students_sorted_by_grade)
# Sort a list of tuples by the second element
pairs = [(1, 9), (4, 2), (2, 5)]
pairs.sort(key=lambda x: x[1])
print("Tuples sorted by second element:", pairs)
Sorted by grade: [{'name': 'Charlie', 'grade': 78}, {'name': 'Alice', 'grade': 85}, {'name': 'Bob', 'grade': 92}]
Tuples sorted by second element: [(4, 2), (2, 5), (1, 9)]
Performance Considerations
Python's sorting algorithm is Timsort. It is a hybrid, stable sorting algorithm derived from merge sort and insertion sort.
It is very efficient for real-world data. The average and worst-case time complexity is O(n log n).
Use sort() for in-place sorting to save memory. Use sorted() when you need the original list intact. For large datasets, ensure your key function is simple and fast.
Common Mistakes and Tips
A common mistake is trying to use sort() on a non-list iterable, like a tuple. Remember, sort() is a list method.
Use sorted() for tuples and strings. Another tip: the key function is called once per item. Avoid heavy operations inside it.
Always verify your list's contents before sorting. Mixing incompatible types (like strings and integers) will cause a TypeError. Understanding your data's Python Array Length: How to Find It and structure is the first step.
Conclusion
Sorting arrays in Python is straightforward and powerful. The list.sort() method sorts a list in-place. The sorted() function returns a new sorted list from any iterable.
Use the reverse parameter for descending order. Use the key parameter for custom sorting logic, especially with lambda functions for complex data.
Mastering these tools allows you to organize data efficiently in any Python project. Start practicing with simple lists and gradually move to more complex structures.