How to sort a list in Python

Syntax:

mylist.sort()

The list object in python has a sort method, that sort the elements of the list.

Example:

input = ['b', 'a', 'c', 'e', 'd']

input.sort()

print( "Sorted list => " + str(input) )

This example create a list with 5 elements, that are not sorted. The list is sorted using the sort method. Once the list is sorted the output is written in the output. Here we will get abcde back.
The method has a optional parameter key that defines the method being used if the Object is the list has several elements.

The output will be:

Sorted list => ['a', 'b', 'c', 'd', 'e']

References:

Python

Share this article:

Recent Comments