Easy Tutorial
❮ Python Func Bytes Python Func Number Pow ❯

Python3 List sort() Method

Python3 List


Description

The sort() function is used to sort the original list. If parameters are specified, it uses the comparison function specified by the parameters.

Syntax

The syntax for the sort() method is:

list.sort(key=None, reverse=False)

Parameters

Return Value

This method does not return any value but sorts the list in place.

Examples

The following examples demonstrate the usage of the sort() function:

#!/usr/bin/python

aList = ['Google', 'tutorialpro', 'Taobao', 'Facebook']

aList.sort()
print("List : ", aList)

Output:

List :  ['Facebook', 'Google', 'tutorialpro', 'Taobao']

The following example demonstrates descending order sorting:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# List
vowels = ['e', 'a', 'u', 'o', 'i']

# Sort in descending order
vowels.sort(reverse=True)

# Output result
print('Descending output:', vowels)

Output:

Descending output: ['u', 'o', 'i', 'e', 'a']

The following example demonstrates sorting by specifying elements in the list:

#!/usr/bin/python

# Function to get the second element of the tuple
def takeSecond(elem):
    return elem[1]

# List
random = [(2, 2), (3, 4), (4, 1), (1, 3)]

# Sort by the second element
random.sort(key=takeSecond)

# Output list
print('Sorted list:', random)

Output:

Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]

Python3 List

❮ Python Func Bytes Python Func Number Pow ❯