Python3 Func Sorted
## Python3 sorted() Function
The built-in `sorted()` function in Python builds a new sorted list from the elements of any iterable. It is a highly versatile and essential tool for data manipulation and sorting operations.
---
### Key Differences: `list.sort()` vs. `sorted()`
* **Scope of Application**:
* `list.sort()` is a method defined exclusively for lists. It cannot be used on other iterables like tuples, dictionaries, sets, or strings.
* `sorted()` is a built-in function that accepts **any iterable** object.
* **In-place vs. New Object**:
* `list.sort()` modifies the original list in-place (mutating it) and returns `None`.
* `sorted()` leaves the original iterable unmodified and returns a **new sorted list**.
* **Performance**:
* If you do not need to preserve the original list, `list.sort()` is slightly more efficient in terms of memory and speed because it does not copy the list.
---
## Syntax
```python
sorted(iterable, key=None, reverse=False)
```
### Parameter Description:
* **`iterable`**: Any iterable object (e.g., `list`, `tuple`, `dict`, `set`, `string`, or generator).
* **`key`**: *(Optional)* A function of one argument that is used to extract a comparison key from each element (e.g., `key=str.lower`, `key=len`, or a custom `lambda` function). The default value is `None` (compare elements directly).
* **`reverse`**: *(Optional)* A boolean value. If set to `True`, the list elements are sorted as if each comparison were reversed (descending order). The default is `False` (ascending order).
### Return Value:
* Returns a **new list** containing all items from the iterable in sorted order.
---
## Code Examples
### 1. Basic Usage (Ascending Order)
By default, `sorted()` sorts elements in ascending order.
```python
# Sorting a list of integers
numbers = [5, 2, 3, 1, 4]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
# Output: [1, 2, 3, 4, 5]
# The original list remains unchanged
print(numbers)
# Output: [5, 2, 3, 1, 4]
```
### 2. Sorting Non-List Iterables
Unlike `list.sort()`, `sorted()` can handle other iterables, such as dictionaries. When sorting a dictionary, it defaults to sorting the keys.
```python
# Sorting dictionary keys
data_dict = {1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}
sorted_keys = sorted(data_dict)
print(sorted_keys)
# Output: [1, 2, 3, 4, 5]
```
### 3. Sorting in Descending Order
You can sort in descending order by setting the `reverse` parameter to `True`.
```python
example_list = [5, 0, 6, 1, 2, 7, 3, 4]
# Sorting in descending order using reverse=True
descending_list = sorted(example_list, reverse=True)
print(descending_list)
# Output: [7, 6, 5, 4, 3, 2, 1, 0]
```
### 4. Custom Sorting with the `key` Parameter
The `key` parameter allows you to define custom sorting logic. In this example, we use a `lambda` function to sort numbers in descending order by negating their values.
```python
example_list = [5, 0, 6, 1, 2, 7, 3, 4]
# Sorting using a custom key function
result_list = sorted(example_list, key=lambda x: x * -1)
print(result_list)
# Output: [7, 6, 5, 4, 3, 2, 1, 0]
```
---
## Advanced Real-World Example: Olympic Medal Standings
Below is a more complex, practical example. We have a raw string containing Olympic medal data (Gold, Silver, and Bronze counts) for 15 countries. We want to parse this data and sort the countries based on their medal counts.
To sort in descending order of medals (highest to lowest) while keeping the default ascending order for country names in case of a tie, we can store the medal counts as negative numbers and sort them using a tuple key.
```python
# Raw data: Country Gold Silver Bronze
raw_data = "Germany 10 11 16\nItaly 10 10 20\nNetherlands 10 12 14\nFrance 10 12 11\nUnited Kingdom 22 21 22\nChina 38 32 18\nJapan 27 14 17\nUSA 39 41 33\nROC 20 28 23\nAustralia 17 7 22\nHungary 6 7 7\nCanada 7 6 11\nCuba 7 3 5\nBrazil 7 6 8\nNew Zealand 7 6 7"
# Split the raw string into lines
medal_rows = raw_data.split('\n', -1)
# Parse data into a dictionary
medal_dict = {}
for row in medal_rows:
data = row.split(' ')
print(data) # Print parsed raw rows
# Convert medal counts to negative integers to sort descending using ascending logic
medal_dict[data] = [int('-' + count) for count in data[1:]]
# Sort the dictionary items:
# Primary key: Medal counts (x) in ascending order (which are negative, so largest positive count comes first)
# Secondary key: Country name (x) in alphabetical order
sorted_standings = sorted(medal_dict.items(), key=lambda x: (x, x))
print()
# Extract and print the final ranked list
ranked_countries = []
for item in sorted_standings:
ranked_countries.append(item)
for rank in range(15):
print(f"{(rank + 1):2d} {ranked_countries}")
```
### Output:
```text
['Germany', '10', '11', '16']
['Italy', '10', '10', '20']
['Netherlands', '10', '12', '14']
['France', '10', '12', '11']
['United Kingdom', '22', '21', '22']
['China', '38', '32', '18']
['Japan', '27', '14', '17']
['USA', '39', '41', '33']
['ROC', '20', '28', '23']
['Australia', '17', '7', '22']
['Hungary', '6', '7', '7']
['Canada', '7', '6', '11']
['Cuba', '7', '3', '5']
['Brazil', '7', '6', '8']
['New Zealand', '7', '6', '7']
1 USA
2 China
3 Japan
4 United Kingdom
5 ROC
6 Australia
7 Netherlands
8 France
9 Germany
10 Italy
11 Canada
12 Brazil
13 New Zealand
14 Cuba
15 Hungary
```
---
## Considerations & Best Practices
1. **Stability**: Python's sorting algorithm (Timsort) is **stable**. This means that when multiple records have equal keys, their original relative order is preserved.
2. **Memory Overhead**: Because `sorted()` returns a brand new list, it requires extra memory to store the copy. If you are working with extremely large datasets and do not need to preserve the original order, use `list.sort()` to save memory.
3. **Key Efficiency**: The `key` function is evaluated exactly once for each input record. This makes key-based sorting highly efficient compared to older comparison methods (like `cmp` in Python 2).
YouTip