In the post, we show how to use Python sorted()
built-in function to sort a Python object list.
Related Posts:
– Python List functions
– Python Sort List of Tuples – using Python sorted() built-in
Python sorted() built-in
sorted()
builds a new sorted list from an iterable.
Method signature ->
sorted(iterable, *, key=None, reverse=False)
Example:
>>> sorted([10, 6, 3, 2, 7]) [2, 3, 6, 7, 10]
Python Class & Object List
– Define Python class:
>>> class Customer: ... def __init__(self, name, age): ... self.name = name ... self.age = age ... def __repr__(self): ... return repr((self.name, self.age)) ...
– Python Object List:
>>> customer_objects = [ ... Customer('Peter', 24), ... Customer('Mary', 18), ... Customer('Jack', 42), ... ]
Python Sort
Using Key Function
sorted()
uses a key
parameter to specify a called function on each list element prior to making comparisons.
>>> sorted(customer_objects, key=lambda customer:customer.age) [('Mary', 18), ('Peter', 24), ('Jack', 42)]
Using Operator Function
Python provides operator
module has itemgetter()
, attrgetter()
, and a methodcaller()
function.
For sorting with objects list, we can use attrgetter()
function ->
>>> from operator import attrgetter >>> >>> sorted(customer_objects, key=attrgetter('age')) [('Mary', 18), ('Peter', 24), ('Jack', 42)]
Ascending and Descending
– Use reverse
parameter with a boolean value.
- case
reverse = False
(default) -> Ascending Sorting - case
reverse = True
-> Descending Sorting
>>> sorted(customer_objects, key=lambda customer:customer.age, reverse=True) [('Jack', 42), ('Peter', 24), ('Mary', 18)]
or
>>> sorted(customer_objects, key=attrgetter('age'), reverse=True) [('Jack', 42), ('Peter', 24), ('Mary', 18)]