Different Ways to Sort() in Python

In Python, sort() is a built-in method used to sort elements in a list in ascending order. It modifies the original list in place, meaning it reorders the elements directly within the list without creating a new list. The sort() method does not return any value; it simply sorts the list and updates it.

  1. Sorting List in Ascending Order
  2. Sorting List in Descending Order
  3. Sort with custom function Using Key
  4. Sorting List of Strings by Length
  5. Sorting List of Tuples by a Specific Element
  6. Sorting List of Dictionaries by a Specific Key

Sort() in Python using Sorting List in Ascending Order

The `sort()` method in Python is used to sort a list of elements in ascending order. It modifies the original list in-place, rearranging its elements to be in increasing numerical or lexicographical order. The method is applicable to lists containing numerical values, strings, or a combination of both. By default, the sort() in Python sorts a list in ascending order if we do not provide it with any parameters.

Example : In this example the below code demonstrates sorting operations on different types of lists. First, it sorts a list of integers (`numbers`) in ascending order using the `sort()` method. Next, it sorts a list of floating-point numbers (`decimalnumber`) in ascending order.

Python3




# List of Integers
numbers = [1, 3, 4, 2]
 
# Sorting list of Integers
numbers.sort()
 
print(numbers)
 
# List of Floating point numbers
decimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68]
 
# Sorting list of Floating point numbers
decimalnumber.sort()
 
print(decimalnumber)
 
# List of strings
words = ["Geeks", "For", "Geeks"]
 
# Sorting list of strings
words.sort()
 
print(words)


Output:

[1, 2, 3, 4]
[1.68, 2.0, 2.01, 3.28, 3.67]
['For', 'Geeks', 'Geeks']

Sort() in Python using Sorting List in Descending Order

To sort a list in descending order, set the reverse parameter to True of the sort() function in Python.

my_list.sort(reverse=True)

Example : In this example code defines three lists of different types (integers, floating-point numbers, and strings), sorts them in descending order using the `sort` method with the `reverse=True` parameter, and then prints the sorted lists.

Python3




# List of Integers
numbers = [1, 3, 4, 2]
 
# Sorting list of Integers
numbers.sort(reverse=True)
 
print(numbers)
 
# List of Floating point numbers
decimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68]
 
# Sorting list of Floating point numbers
decimalnumber.sort(reverse=True)
 
print(decimalnumber)
 
# List of strings
words = ["Geeks", "For", "Geeks"]
 
# Sorting list of strings
words.sort(reverse=True)
 
print(words)


Output:

[4, 3, 2, 1]
[3.67, 3.28, 2.01, 2.0, 1.68]
['Geeks', 'Geeks', 'For']

Sort with Custom Function Using Key

In this method describes a sorting operation with a custom function using the “key” parameter. This allows sorting based on a specific criterion defined by the custom function rather than the default ordering. The custom function is applied to each element, and the list is sorted accordingly.

Example : In this example code defines a function `sortSecond` that returns the second element of a tuple. It then creates a list of tuples, `list1`, and sorts it in ascending order based on the second element using the `sortSecond` function.

Python3




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)]

Sorting List of Strings by Length in Sort() in Python

In this method we sorts a list of strings in ascending order of their lengths using the `sort()` function with the `key=len`. This means that the strings are arranged from the shortest to the longest length in the resulting sorted list.

Example : In this example the below code defines a list of strings, words, and then sorts it based on the length of each string using the len() function as the sorting key. Finally, it prints the sorted list.

Python3




# Original list of strings
words = ["apple", "banana", "kiwi", "orange", "grape"]
 
# Sorting by length using the len() function as the key
words.sort(key=len)
 
# Displaying the sorted list
print("Sorted by Length:", words)


Output :

Sorted by Length: ['kiwi', 'apple', 'grape', 'banana', 'orange']

Sorting List of Tuples by a Specific Element

To sort a list of tuples by a specific element, use the `sort()` function with the `key` parameter. Specify a lambda function as the key, targeting the desired element’s index. The tuples will be sorted based on the values of that specific element.

Example : In this method code defines a list of tuples named ‘people,’ where each tuple represents a person’s name and age. It then sorts the list based on the second element of each tuple (age) using the sort method and a lambda function as the sorting key.

Python3




# Original list of tuples
people = [("Alice", 25), ("Bob", 30), ("Charlie", 22), ("David", 28)]
 
# Sorting by the second element of each tuple (age)
people.sort(key=lambda x: x[1])
 
# Displaying the sorted list
print("Sorted by Age:", people)


Output :

Sorted by Age: [('Charlie', 22), ('Alice', 25), ('David', 28), ('Bob', 30)]

Sorting List of Dictionaries by a Specific Key

This method involves using the `sort()` function on a list of dictionaries in Python. By specifying a lambda function as the key parameter, you can sort the list based on a specific key within each dictionary. This enables the list of dictionaries to be arranged in ascending order according to the values associated with the chosen key.

Example : In this example code defines a list of dictionaries called students, where each dictionary represents a student with “name” and “age” keys. It then sorts the list of dictionaries based on the “age” key in each dictionary using the sort method and a lambda function as the key.

Python3




# Original list of dictionaries
students = [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 30},
    {"name": "Charlie", "age": 22},
    {"name": "David", "age": 28},
]
 
# Sorting by the 'age' key in each dictionary
students.sort(key=lambda x: x["age"])
 
# Displaying the sorted list
print("Sorted by Age:", students)


Output :

Sorted by Age: [
{'name': 'Charlie', 'age': 22},
{'name': 'Alice', 'age': 25},
{'name': 'David', 'age': 28},
{'name': 'Bob', 'age': 30}
]

sort() in Python

The sort function can be used to sort the list in both ascending and descending order. It can be used to sort lists of integers, floating point numbers, strings, and others in Python. Its time complexity is O(NlogN).

Similar Reads

Python sort() Syntax

The syntax of the sort() function in Python is as follows....

What is Python sort() Function?

In Python, the sort() function is a method that belongs to the list . It is used to sort in python or the elements of a list in ascending order by default. The sort() method modifies the original list in-place, meaning it rearranges the elements directly within the existing list object, rather than creating a new sorted list....

Sort() in Python Examples

A basic example of Python sort() method....

Different Ways to Sort() in Python

...

Difference between sorted() and sort() function in Python

In Python, sort() is a built-in method used to sort elements in a list in ascending order. It modifies the original list in place, meaning it reorders the elements directly within the list without creating a new list. The sort() method does not return any value; it simply sorts the list and updates it....