Python: Sort a list/tuple/class by specific field

This is something that I have to do every once in a while and can never remember the method. To save myself some time, I've written this here in hope that I can remember it next time.

student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]

# sort by age
sorted(student_tuples, key = lambda student: student[2])

[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

This great example is straight from the Python wiki page.

[ Source ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog