Skip to content

Commit 21cbfc7

Browse files
authored
[Edit] Python Built-in Functions: sorted() (#7401)
* [Edit] Python Built-in Functions: sorted() * minor fixes and changed one faq based on PAA ---------
1 parent 1e65c2f commit 21cbfc7

File tree

1 file changed

+41
-85
lines changed
  • content/python/concepts/built-in-functions/terms/sorted

1 file changed

+41
-85
lines changed
Lines changed: 41 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -1,140 +1,96 @@
11
---
22
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.'
44
Subjects:
5-
- 'Data Science'
65
- 'Computer Science'
6+
- 'Data Science'
77
Tags:
8-
- 'Strings'
98
- 'Functions'
109
- 'Iterators'
1110
- 'Lists'
11+
- 'Strings'
1212
CatalogContent:
1313
- 'learn-python-3'
1414
- 'paths/analyze-data-with-python'
1515
---
1616

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.
1818

19-
## Syntax
19+
## Python `sorted()` Syntax
2020

2121
```pseudo
2222
sorted(iterable, key=None, reverse=False)
2323
```
2424

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:**
2626

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.
2830

29-
`sorted()` can be used on either numbers or letters, but not on a combination of the two:
31+
**Return value:**
3032

31-
```python
32-
my_list = ["beta", "epsilon", "alpha", "delta", "gamma"]
33+
Returns a list that includes the elements in the iterable in sorted order.
3334

34-
new_list = sorted(my_list)
35+
## Example 1: Sorting a List Using `sorted()` Function in Python
3536

36-
print(new_list)
37-
# Output: ['alpha', 'beta', 'delta', 'epsilon', 'gamma']
38-
```
37+
This example uses `sorted()` to sort the `my_list` list:
3938

40-
```python
41-
my_list = [7,2,3,5,1,4,6]
39+
```py
40+
my_list = ["beta", "epsilon", "alpha", "delta", "gamma"]
4241

4342
new_list = sorted(my_list)
4443

4544
print(new_list)
46-
# Output: [1, 2, 3, 4, 5, 6, 7]
4745
```
4846

49-
## Example 2
50-
51-
Changing the `reverse` parameter changes the order of the sort:
47+
Here is the output:
5248

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']
6051
```
6152

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()`
6554

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:
6856

69-
after_sorted = sorted(my_string)
57+
```py
58+
my_list = [7, 2, 3, 5, 1, 4, 6]
7059

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)
7561

76-
print(after_sorted)
77-
# Output: ['a', 'b', 'C', 'd', 'E']
62+
print(new_list)
7863
```
7964

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:
9166

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]
9669
```
9770

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
10772

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:
10974

110-
print(my_sorted_list)
111-
# Output: [1, 2, 3, 4]
75+
```codebyte/python
76+
words = ["banana", "apple", "cherry", "date"]
11277
113-
my_sorted_list = sorted(my_list, key=sorting_func)
78+
sorted_words = sorted(words, key=len)
11479
115-
print(my_sorted_list)
116-
# Output: [4, 3, 2, 1]
80+
print(sorted_words)
11781
```
11882

119-
## Codebyte Example
83+
## Frequently Asked Questions
12084

121-
Sorting a list of dictionaries based on a specific key:
85+
### 1. What is the difference between `sorted()` and `list.sort()`?
12286

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`.
13089

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()`?
13391

134-
print(sorted_list)
92+
Yes, you can set the `reverse` parameter in `sorted()` to `True` to sort in descending order.
13593

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?
13895

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

Comments
 (0)