How to Python list sort()

Python list is a collection which is ordered and changeable. It can holds a number of other objects, in a given order. List is a compound data type which means you can have different data types under a list, for ex. you can have integer, float and string items in a same list. Also, the list type implements the sequence protocol , so it allows you to add and remove objects from the sequence.

How to Python list sort

List sort()

The sort() method performs the sorting of list elements in ascending , descending or user defined order . When we call sort() method, it traverses the list elements in a loop and rearranges them in ascending order when there are no arguments. When we pass reverse = true , then the list gets sorted in the descending order.


  1. reverse - Default is reverse=False, while reverse=True will sort the list descending.(Optional)

  2. key - A method to specify the sorting criteria (Optional)

Sort list of numbers

python list sort alphabetically

Sort list of strings

python list sort ascending

Sort list of strings in descending order


If any of the list element is Uppercase , let's see what happens.

python list sort descending order

It is because Python treats all Uppercase letters to be lower than Lowercase letters, if you want you can change it.


python list sort lambda

Sort using key parameter

The key parameter in sort() method specifies a function that will be called on each list item before making comparisons. If you want your own implementation for sorting , you can use key parameter as an optional parameter.


Sort using key parameter (reverse)


Sort the list by the length of the values

A new function "sortLen" that returns the length of the list elements and add this function as key of sort() function.


Sorting a List of Tuples

A Tuple is a collection of Python objects that written with round brackets and separated by commas. The difference between Tuple and List is that we cannot change the elements of a tuple once it is assigned whereas, in a list, elements can be changed.

Sorting a List of Tuples by the first item


Sorting a List of Tuples by the second item


Sorting a list of objects

 (C) 2020    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About