Python – Sort Python List of Tuples – using Python sorted() built-in

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

Start

Python sorted() built-in

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

Method signature -> sorted(iterable, key=keyfunc, reverse=True)

Example:

Python List of Tuples

Python Tuples:

  • A tuple is a collection which is ordered and unchangeable.
  • Python tuples are written with round brackets ().

Example list of tuples ->

Python Sort List of Tuples

Sorted with Key Function

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

Sorted with Operator Function

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

Sorted with Ascending and Descending

– Use reverse parameter with a boolean value.

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

or

Complex Sorts with Multi Steps

Python sorted() will preverse the original order of records having the same key.

-> Example:

-> Before and After sorting, ('apple', 3)(('samsung', 5)) is guaranteed to precede ('apple', 4) (('samsung', 1))

Now we can build complex sorts in a series of sorting steps with difference key function:



By grokonez | July 17, 2018.


Related Posts


Got Something To Say:

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

*