|
1 | 1 | ---
|
2 | 2 | Title: 'sorted()'
|
3 |
| -Description: 'Takes in an iterator object, such as a list, tuple, dictionary, set, or string, and sorts it according to a parameter.' |
| 3 | +Description: 'Returns a new sorted list from the elements of any iterable, without modifying the original.' |
4 | 4 | Subjects:
|
5 |
| - - 'Data Science' |
6 | 5 | - 'Computer Science'
|
| 6 | + - 'Data Science' |
7 | 7 | Tags:
|
8 |
| - - 'Strings' |
9 | 8 | - 'Functions'
|
10 | 9 | - 'Iterators'
|
11 | 10 | - 'Lists'
|
| 11 | + - 'Strings' |
12 | 12 | CatalogContent:
|
13 | 13 | - 'learn-python-3'
|
14 | 14 | - 'paths/analyze-data-with-python'
|
15 | 15 | ---
|
16 | 16 |
|
17 |
| -Takes in an iterator object, such as a list, tuple, dictionary, set, or string, and sorts it according to a parameter. |
| 17 | +Python's **`sorted()`** [function](https://www.codecademy.com/resources/docs/python/functions) takes in an [iterable](https://www.codecademy.com/resources/docs/python/iterators) object, such as a [list](https://www.codecademy.com/resources/docs/python/lists), [tuple](https://www.codecademy.com/resources/docs/python/tuples), [dictionary](https://www.codecademy.com/resources/docs/python/dictionaries), [set](https://www.codecademy.com/resources/docs/python/sets), or [string](https://www.codecademy.com/resources/docs/python/strings), and sorts it according to a parameter. This function is versatile, easy to use, and supports custom sorting logic using optional parameters. |
18 | 18 |
|
19 |
| -## Syntax |
| 19 | +## Python `sorted()` Syntax |
20 | 20 |
|
21 | 21 | ```pseudo
|
22 | 22 | sorted(iterable, key=None, reverse=False)
|
23 | 23 | ```
|
24 | 24 |
|
25 |
| -The `key` and `reverse` parameters are optional, and will default to `None` and `False`. `False` sorts ascending, and `True` descending. The `key` takes an input function to determine the comparison key. |
| 25 | +**Parameters:** |
26 | 26 |
|
27 |
| -## Example 1 |
| 27 | +- `iterable`: The sequence (list, tuple, string, dictionary, etc.) to be sorted. |
| 28 | +- `key` (Optional): A function that acts as a sorting key. |
| 29 | +- `reverse` (Optional): If `True`, the result is sorted in descending order. |
28 | 30 |
|
29 |
| -`sorted()` can be used on either numbers or letters, but not on a combination of the two: |
| 31 | +**Return value:** |
30 | 32 |
|
31 |
| -```python |
32 |
| -my_list = ["beta", "epsilon", "alpha", "delta", "gamma"] |
| 33 | +Returns a list that includes the elements in the iterable in sorted order. |
33 | 34 |
|
34 |
| -new_list = sorted(my_list) |
| 35 | +## Example 1: Sorting a List Using `sorted()` Function in Python |
35 | 36 |
|
36 |
| -print(new_list) |
37 |
| -# Output: ['alpha', 'beta', 'delta', 'epsilon', 'gamma'] |
38 |
| -``` |
| 37 | +This example uses `sorted()` to sort the `my_list` list: |
39 | 38 |
|
40 |
| -```python |
41 |
| -my_list = [7,2,3,5,1,4,6] |
| 39 | +```py |
| 40 | +my_list = ["beta", "epsilon", "alpha", "delta", "gamma"] |
42 | 41 |
|
43 | 42 | new_list = sorted(my_list)
|
44 | 43 |
|
45 | 44 | print(new_list)
|
46 |
| -# Output: [1, 2, 3, 4, 5, 6, 7] |
47 | 45 | ```
|
48 | 46 |
|
49 |
| -## Example 2 |
50 |
| - |
51 |
| -Changing the `reverse` parameter changes the order of the sort: |
| 47 | +Here is the output: |
52 | 48 |
|
53 |
| -```python |
54 |
| -my_list = [7,2,3,5,1,4,6] |
55 |
| - |
56 |
| -new_list = sorted(my_list, reverse=True) |
57 |
| - |
58 |
| -print(new_list) |
59 |
| -# Output: [7, 6, 5, 4, 3, 2, 1] |
| 49 | +```shell |
| 50 | +['alpha', 'beta', 'delta', 'epsilon', 'gamma'] |
60 | 51 | ```
|
61 | 52 |
|
62 |
| -## Example 3 |
63 |
| - |
64 |
| -When `reversed` is `False`, `sorted()` will sort numbers from low to high, and letters alphabetically. However, capital letters will come before lowercase letters. In order to sort all objects with the same key, use a function with the key `parameter`: |
| 53 | +## Example 2: Sorting in Descending Order Using `sorted()` |
65 | 54 |
|
66 |
| -```python |
67 |
| -my_string = "bCEad" |
| 55 | +This example uses `sorted()` with the `reverse` parameter set to `True` to sort the `my_list` list in descending order: |
68 | 56 |
|
69 |
| -after_sorted = sorted(my_string) |
| 57 | +```py |
| 58 | +my_list = [7, 2, 3, 5, 1, 4, 6] |
70 | 59 |
|
71 |
| -print(after_sorted) |
72 |
| -# Output: ['C', 'E', 'a', 'b', 'd'] |
73 |
| - |
74 |
| -after_sorted = sorted(my_string, key=str.lower) |
| 60 | +new_list = sorted(my_list, reverse=True) |
75 | 61 |
|
76 |
| -print(after_sorted) |
77 |
| -# Output: ['a', 'b', 'C', 'd', 'E'] |
| 62 | +print(new_list) |
78 | 63 | ```
|
79 | 64 |
|
80 |
| -## Example 4 |
81 |
| - |
82 |
| -The `key` parameter can also be used to sort by other comparisons, such as length: |
83 |
| - |
84 |
| -```python |
85 |
| -my_list = ["aaa", "bb", "c"] |
86 |
| - |
87 |
| -my_sorted_list = sorted(my_list) |
88 |
| - |
89 |
| -print(my_sorted_list) |
90 |
| -# Output: ['aaa', 'bb', 'c'] |
| 65 | +Here is the output: |
91 | 66 |
|
92 |
| -my_sorted_list = sorted(my_list, key=len) |
93 |
| - |
94 |
| -print(my_sorted_list) |
95 |
| -# Output: ['c', 'bb', 'aaa'] |
| 67 | +```shell |
| 68 | +[7, 6, 5, 4, 3, 2, 1] |
96 | 69 | ```
|
97 | 70 |
|
98 |
| -## Example 5 |
99 |
| - |
100 |
| -The `key` parameter can even take in custom functions: |
101 |
| - |
102 |
| -```python |
103 |
| -def sorting_func(i): |
104 |
| - return i - i**2 |
105 |
| - |
106 |
| -my_list = [2,1,4,3] |
| 71 | +## Codebyte Example: Using Python's `sorted()` with a Key |
107 | 72 |
|
108 |
| -my_sorted_list = sorted(my_list) |
| 73 | +This codebyte example uses `sorted()` with the `key` parameter set to `len` to sort the `words` list based on the length of its items: |
109 | 74 |
|
110 |
| -print(my_sorted_list) |
111 |
| -# Output: [1, 2, 3, 4] |
| 75 | +```codebyte/python |
| 76 | +words = ["banana", "apple", "cherry", "date"] |
112 | 77 |
|
113 |
| -my_sorted_list = sorted(my_list, key=sorting_func) |
| 78 | +sorted_words = sorted(words, key=len) |
114 | 79 |
|
115 |
| -print(my_sorted_list) |
116 |
| -# Output: [4, 3, 2, 1] |
| 80 | +print(sorted_words) |
117 | 81 | ```
|
118 | 82 |
|
119 |
| -## Codebyte Example |
| 83 | +## Frequently Asked Questions |
120 | 84 |
|
121 |
| -Sorting a list of dictionaries based on a specific key: |
| 85 | +### 1. What is the difference between `sorted()` and `list.sort()`? |
122 | 86 |
|
123 |
| -```codebyte/python |
124 |
| -my_list_of_dicts = [ |
125 |
| - {"name": "Alice", "age": 30}, |
126 |
| - {"name": "Bob", "age": 25}, |
127 |
| - {"name": "Charlie", "age": 35}, |
128 |
| - {"name": "David", "age": 28} |
129 |
| -] |
| 87 | +- `sorted()` works on any iterable and returns a new sorted list. |
| 88 | +- `list.sort()` modifies the list in-place and returns `None`. |
130 | 89 |
|
131 |
| -# Sort the list of dictionaries based on the "age" key in ascending order |
132 |
| -sorted_list = sorted(my_list_of_dicts, key=lambda x: x["age"]) |
| 90 | +### 2. Can I sort in descending order using `sorted()`? |
133 | 91 |
|
134 |
| -print(sorted_list) |
| 92 | +Yes, you can set the `reverse` parameter in `sorted()` to `True` to sort in descending order. |
135 | 93 |
|
136 |
| -# Sort the list of dictionaries based on the "name" key in alphabetical order (case-insensitive) |
137 |
| -sorted_list_by_name = sorted(my_list_of_dicts, key=lambda x: x["name"].lower()) |
| 94 | +### 3. Does `sorted()` always return a list? |
138 | 95 |
|
139 |
| -print(sorted_list_by_name) |
140 |
| -``` |
| 96 | +Yes, no matter what iterable you pass in—whether it’s a string, tuple, set, or dictionary, `sorted()` always returns a new list containing the sorted elements. It never returns the same type as the input. |
0 commit comments