Python Sort Class Object List – with Python sorted()

In the post, we show how to use Python sorted() built-in function to sort a Python object list.

Python sorted() built-in

sorted() builds a new sorted list from an iterable.

Method signature ->

sorted(iterable, *, key=None, reverse=False)

Example:

Python Class & Object List

– Define Python class:

– Python Object List:

Python Sort

Using Key Function

sorted() uses a key parameter to specify a called function on each list element prior to making comparisons.

Using Operator Function

Python provides operator module has itemgetter(), attrgetter(), and a methodcaller() function.
For sorting with objects list, we can use attrgetter() function ->

Ascending and Descending

– Use reverse parameter with a boolean value.

  • case reverse = False (default) -> Ascending Sorting
  • case reverse = True -> Descending Sorting

or



By grokonez | July 16, 2018.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*