Monday, September 23, 2024
Google search engine
HomeLanguagesPython List sort() Method

Python List sort() Method

Python list sort() function can be used to sort List with Python in ascending, descending, or user-defined order. In each case, the time complexity is O(nlogn) in Python.

Python List sort() Syntax

To sort the list in Python, we use the sort() function in Python.

Syntax: List_name.sort(reverse=True/False, key=myFunc)

Parameter:

  • reverse: (Optional), reverse=True will sort the list descending. Default is reverse=False
  • key Optional. A function to specify the sorting criteria(s)

List sort() in Python Examples 

In the example, we will see different examples to apply Python sort() methods.

Example 1: Sort a List of Numbers in Ascending Order

The sort() method by default sort element in ascending order as we can see below example:

Python3




numbers = [1, 3, 4, 2]
  
# Sorting list of Integers in ascending
print(numbers.sort()) 
print(numbers)                      


Output :

None
[1, 2, 3, 4]

Example 2: Sort a List of Alphabets In Ascending Order

The sort() method sorts the list in order from A-Z, to a-z in the alphabet. 

Python3




# Sorting List in Descending Order
# Creating List
strs = ["Lazyroar", "code", "ide", "practice"]
  
# Sorting list of Integers in ascending
# using sort() methods
strs.sort()
print(strs)


Output :

['code', 'Lazyroar', 'ide', 'practice']

Example 3: Sort a List in Descending Order 

Here, we are sorting the list of numbers in Descending order, the same will be for alphabets(Z-A, z-a). To do this we need to pass reverse=True, this will sort numbers or the alphabet in descending Order.

Python3




# Python program to demonstrate to
# sorting numbers in descending Order
# Creating List of Numbers
numbers = [1, 3, 4, 2]
  
# Sorting list of Integers in descending
numbers.sort(reverse=True)
  
print(numbers)


Output :

[4, 3, 2, 1]

Example 4: Sort the list  by key 

In this example, we are sorting elements using the function based on passing the function to the key parameter of the sort() function.

Python3




# function to return the second element of the
# two elements passed as the parameter
def sortSecond(val):
    return val[1]
  
# list1 to demonstrate the use of sorting
# using  second key
list1 = [(1, 2), (3, 3), (1, 1)]
  
# sorts the array in ascending according to
# second element
list1.sort(key=sortSecond)
print(list1)
  
# sorts the array in descending according to
# second element
list1.sort(key=sortSecond, reverse=True)
print(list1)


Output :

[(1, 1), (1, 2), (3, 3)]
[(3, 3), (1, 2), (1, 1)]

The difference between sort() and sorted() is that the sort list in Python alters the list directly and produces no output, whereas sorted() doesn’t change the list and returns the sorted list.

RELATED ARTICLES

Most Popular

Recent Comments