Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 77513af

Browse files
Create 07_sort().MD
1 parent 2b6f115 commit 77513af

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

‎Lecture_17/07_sort().MD

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# **`sort()`**
2+
3+
* sort() method = used with lists
4+
* sort() functions = used with iterables
5+
6+
```py
7+
students = ['spongebob', 'sandy', 'patrick', 'squidward', 'mr.krab']
8+
students.sort()
9+
for i in students:
10+
print(i)
11+
## to reverse
12+
students.sort(reverse=True)
13+
```
14+
15+
if we use:
16+
`students = ('spongebob', 'sandy', 'patrick', 'squidward', 'mr.krab')`
17+
It will throw an error of AttributeError: 'tuple' object has no attribute 'sort'
18+
To sort this we need the built in functions:
19+
20+
```py
21+
sorted_students = sorted(students)
22+
for i in sorted_students:
23+
print(i)
24+
```
25+
26+
To reverse it we will use :- `sorted(students, reverse = True)`
27+
28+
Suppose we have list of tuples:
29+
```py
30+
students = [("Squidward", "F", 60), ("Sandy", "A", 33), ("Patrick", "D", 36),("Spongebob", "B", 20), ("Mr. Krab", "C", 78)]
31+
grades = lambda grades:grades[1]
32+
ages = lambda ages:ages[2]
33+
students.sort(key = grades)
34+
for i in students:
35+
print(i)
36+
37+
students.sort(key = grades, reverse = True)
38+
```
39+
40+
Now, suppose we have the list of the list:-
41+
42+
```py
43+
students = (("Squidward", "F", 60), ("Sandy", "A", 33), ("Patrick", "D", 36),("Spongebob", "B", 20), ("Mr. Krab", "C", 78))
44+
ages = lambda ages:ages[2]
45+
sorted_students = sorted(students, key=ages)
46+
for i in sorted_students:
47+
print(i)
48+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /