Python Sorting Basics
Python Sorting Basics
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.
`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]
You can sort data using a custom key by providing a function or a lambda function to the `key`
parameter.
python
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/4
python
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]
python
Sorting dictionaries: By default, dictionaries are unordered (pre-Python 3.7). You can sort by
keys or values.
python
python
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
Example:
python
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.
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.
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