1#1 Changes list
2list.sort(reverse=True)
3#2 Returns sorted list
4sorted(list, reverse=True)
1>>> student_tuples = [
2... ('john', 'A', 15),
3... ('jane', 'B', 12),
4... ('dave', 'B', 10),
5... ]
6>>> sorted(student_tuples, key=lambda student: student[2])
7# sort by age
8[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
9
1>>> sorted(student_tuples, key=itemgetter(2))
2[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
3
1>>> student_tuples = [
2... ('john', 'A', 15),
3... ('jane', 'B', 12),
4... ('dave', 'B', 10),
5... ]
6>>> sorted(student_tuples, key=lambda student: student[2]) # sort by age
7[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
8
1>>> class Student:
2... def __init__(self, name, grade, age):
3... self.name = name
4... self.grade = grade
5... self.age = age
6... def __repr__(self):
7... return repr((self.name, self.grade, self.age))
8
1>>> student_objects = [
2... Student('john', 'A', 15),
3... Student('jane', 'B', 12),
4... Student('dave', 'B', 10),
5... ]
6>>> sorted(student_objects, key=lambda student: student.age) # sort by age
7[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
8