Python: Various ways to sort lists and tuples

I was amazed to how many ways there were to sort lists in Python. Better yet, you DON'T need to create a new function to sort things like you do in PHP.

Basic Sorting

Create a copy of the list

sorted([5, 2, 3, 1, 4])

[1, 2, 3, 4, 5]

Sort and modify the list

This method only works for lists.

a = [5, 2, 3, 1, 4]

[1, 2, 3, 4, 5]

Sort by Key

Pyhon 2.4 brings the "key" argument to sorted().

For example, we use the tuple:

student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
sorted(student_tuples, key=lambda student: student[2]) # sort by age

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

Or a class:

class Student:
def __init__(self, name, grade, age): = name
self.grade = grade
self.age = age

student_objects = [
Student('john', 'A', 15),
Student('jane', 'B', 12),
Student('dave', 'B', 10),
sorted(student_objects, key=lambda student: student.age) # sort by age

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

Sort by key has some helper functions called itemgetter() and attrgetter() which do what the above examples do. It also allows for multiple levels of sorting.

from operator import itemgetter, attrgetter

sorted(student_tuples, key=itemgetter(1,2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

Reverse order

Easy enough, there's a "reverse" argument in sorted() to do that.

sorted(a, reverse = True)


This post was an extract of the things I found helpful from the Python wiki docs. See the link below for more information.

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