Python Sorting Basics
can you teach me all about sorting in python?
Certainly! Sorting is a fundamental concept in programming, and Python provides powerful tools and
methods to sort data efficiently. Let's break it down step by step.
1. Basic Sorting with `sorted()` and `.sort()`
`sorted()` function: This returns a new sorted list from the elements of any iterable (e.g., list,
tuple, string).
python
numbers = [3, 1, 4, 1, 5, 9]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 1, 3, 4, 5, 9]
`.sort()` method: This sorts a list in place, modifying the original list.
python
numbers = [3, 1, 4, 1, 5, 9]
numbers.sort()
print(numbers) # Output: [1, 1, 3, 4, 5, 9]
2. Custom Sorting with `key`
You can sort data using a custom key by providing a function or a lambda function to the `key`
parameter.
Sorting by length of strings:
python
words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words, key=len)
print(sorted_words) # Output: ['date', 'apple', 'banana', 'cherry']
Sorting by custom criteria (e.g., by length, then alphabetically):
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/4
python
words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words, key=lambda word: (len(word), word))
print(sorted_words) # Output: ['date', 'apple', 'banana', 'cherry']
3. Reverse Sorting
Both `sorted()` and `.sort()` have a `reverse` parameter to sort in descending order.
python
numbers = [3, 1, 4, 1, 5, 9]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers) # Output: [9, 5, 4, 3, 1, 1]
4. Sorting Complex Data Structures
Sorting a list of tuples (e.g., sorting by the second element):
python
items = [(1, 'one'), (3, 'three'), (2, 'two')]
sorted_items = sorted(items, key=lambda x: x[1])
print(sorted_items) # Output: [(1, 'one'), (3, 'three'), (2, 'two')]
Sorting dictionaries: By default, dictionaries are unordered (pre-Python 3.7). You can sort by
keys or values.
python
data = {'apple': 2, 'banana': 3, 'cherry': 1}
sorted_by_key = sorted(data.items())
print(sorted_by_key) # Output: [('apple', 2), ('banana', 3), ('cherry', 1)]
sorted_by_value = sorted(data.items(), key=lambda item: item[1])
print(sorted_by_value) # Output: [('cherry', 1), ('apple', 2), ('banana', 3)]
5. Advanced Sorting Techniques
Multi-level sorting: Using tuples in the `key` to sort by multiple criteria.
python
people = [("Alice", 25), ("Bob", 30), ("Charlie", 25), ("David", 30)]
sorted_people = sorted(people, key=lambda x: (x[1], x[0]))
print(sorted_people) # Output: [('Alice', 25), ('Charlie', 25), ('Bob', 30),
('David', 30)]
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/4
Sorting with custom order: If you want to sort based on a custom sequence, you can use a
dictionary to map values to their desired order.
python
priority = {'low': 3, 'medium': 2, 'high': 1}
tasks = ['low', 'medium', 'high', 'medium']
sorted_tasks = sorted(tasks, key=lambda x: priority[x])
print(sorted_tasks) # Output: ['high', 'medium', 'medium', 'low']
6. Sorting with `key=lambda name: (-len(name), name[::-1])`
This expression combines two sorting criteria:
`-len(name)` sorts by length in descending order (longer names first).
`name[::-1]` sorts alphabetically by the reversed string if lengths are equal.
Example:
python
names = ["Alice", "Bob", "Charlie", "Dave"]
sorted_names = sorted(names, key=lambda name: (-len(name), name[::-1]))
print(sorted_names) # Output: ['Charlie', 'Alice', 'Dave', 'Bob']
Here, `Charlie` and `Alice` are both sorted by length first (descending), and then `Alice` appears
before `Dave` because the reversed 'ecilA' comes before 'evaD'.
7. Performance Considerations
Timsort: Python's built-in sort algorithm (`sorted()` and `.sort()`) is Timsort, which is a hybrid
sorting algorithm derived from merge sort and insertion sort. It has a time complexity of O(n log
n) and performs well on real-world data.
Stability: Python's sort is stable, meaning that when two records have equal keys, their original
order is preserved.
8. In-place vs. Out-of-place Sorting
In-place (`.sort()`): Modifies the original list.
Out-of-place (`sorted()`): Creates a new sorted list, leaving the original list unchanged.
9. Sorting in Other Contexts
Sorting strings: Strings can be sorted, treating them as sequences of characters.
python
string = "python"
sorted_string = sorted(string)
print(sorted_string) # Output: ['h', 'n', 'o', 'p', 't', 'y']
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/4
Sorting with different data types: Sorting a list containing mixed data types can be tricky and
often results in errors unless a consistent key is provided.
10. Practice Problems
Sort a list of dictionaries by a specific key.
Sort a list of tuples by multiple criteria.
Sort a list of strings by their last letter.
Would you like to dive deeper into any of these topics or see more examples?
ChatGPT can make mistakes. Check important info.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/4