Skip to content

Commit a870f2a

Browse files
author
Joseph Luce
authored
Create sorting.md
1 parent e18fa59 commit a870f2a

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Diff for: pythonic/sorting.md

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
This section, I'll be going over the best ways to sort in Python.
2+
3+
## Sorting a list of integers
4+
5+
sorted() creates a new list after the sort.
6+
```
7+
result = [3,4,2,1,5]
8+
sorted(result)
9+
>>> [1,2,3,4,5]
10+
```
11+
12+
.sort() sorts the exisiting list in-place, therefore modifying the list.
13+
```
14+
result = [3,4,2,1,5]
15+
result.sort()
16+
print(result)
17+
>>> [1,2,3,4,5]
18+
```
19+
20+
To sort in reverse, pass in the reverse keyword as True.
21+
```
22+
sorted(result, reverse=True)
23+
```
24+
```
25+
result.sort(reverse=True)
26+
```
27+
28+
## Sorting a list of tuples
29+
```
30+
result = [(1,3),(1,2),(2,3),(2,1),(1,1)]
31+
result.sort()
32+
```
33+
34+
Sorting a list of tuples based on a specific value per tuple
35+
36+
```
37+
result.sort(key=lambda x: x[1])
38+
```
39+
40+
Sorting a list of tuples with tiebreaker.
41+
42+
```
43+
result.sort(key=lambda x: (x[0], x[1]))
44+
```
45+
46+
Sorting a list of tuples with tiebreaker but second value is sorted in reversed.
47+
```
48+
result.sort(key=lambda x: (x[0], -x[1]))
49+
>>> [(1, 3), (1, 2), (1, 1), (2, 3), (2, 1)]
50+
```
51+
## Sorting a list of tuples which contain strings
52+
53+
## Sorting based on a custom sort

0 commit comments

Comments
 (0)