Net-informations.com

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.

Syntax

  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

output

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.

key=str.lower


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.

output

Sort using key parameter (reverse)

output

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.

output

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

output

Sorting a List of Tuples by the second item

output

Sorting a list of objects

output










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