Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Sorting List in Python | List Sort, Example

Sorting list in Python means arranging Elements in a particular order, either in ascending or descending order.

While working with data in Python, it is often essential to Sort lists. Python provides several built-in methods to sort lists.

In this tutorial, we will learn the various ways to sort a list in Python, from the simplest to the most complex. We will discuss some of the commonly used techniques for sorting a list.

Sorting a List in Python using sort() Function


Python provides a built-in Function named sort() to sort a list in ascending order. By default, it sorts the list elements in ascending order. This function sorts the list of elements in the place, modifying the original list.

Here is a simple example of sorting a list of string elements using the sort() method:

Example 1:

# Creating a list of seven elements of type string.
fruits = ['apple', 'banana', 'dates', 'kiwi', 'grape', 'orange', 'cherry']

# Calling sort() function to sort list in ascending order.
fruits.sort()

# Displaying the list.
print("List of elements in ascending order:")
print(fruits)
Output:
      List of elements in ascending order:
      ['apple', 'banana', 'cherry', 'dates', 'grape', 'kiwi', 'orange']

We can also sort elements of list in descending order by passing the reverse = True parameter to the sort() function.

Example 2:

# Creating a list of six elements of type string.
fruits = ['apple', 'banana', 'dates', 'kiwi', 'grape', 'orange']

# Calling sort() function to sort list in descending order.
fruits.sort(reverse=True)

# Displaying the list.
print("List of elements in descending order:")
print(fruits)
Output:
      List of elements in descending order:
      ['orange', 'kiwi', 'grape', 'dates', 'banana', 'apple']

Sorting a List in Descending Order


To sort a list in descending order, we will have to use both sort() and reverse() functions simultaneously. Here is a simple example of sorting a list of elements in descending order using reverse() function.

Example 3:

# Creating a list of unsorted numbers.
num_list = [30, 10, 40, 50, 90, 20, 60, 30]

# Sorting a list of numbers in descending order.
num_list.sort()
num_list.reverse()

# Displaying a list of sorted elements.
print("Sorted list elements in descending order: ")
print(num_list)
Output:
       Sorted list elements in descending order: 
       [90, 60, 50, 40, 30, 30, 20, 10]

How to Sort a List using sorted() Function


Python language provides a built-in sorted() function to sort any iterable objects, like a list, dictionary, or string. This function takes an iterable object and returns a new sorted list. However, the original list remains unchanged.

Here is a simple example of sorting a list of integer elements using the sorted() function:

Example 4:

# Creating a list of six elements of type integer.
nums = [7, 5, 3, 2, 8, 6]

# Calling sorted() function to sort a list in ascending order.
sorted_nums = sorted(nums)

# Displaying the list.
print("List of elements in ascending order:")
print(sorted_nums)
Output:
       List of elements in ascending order:
       [2, 3, 5, 6, 7, 8]

We can also sort elements of list in descending order by passing the reverse = True parameter to the sorted() function. Look at the simple example below.

Example 5:

# Creating a list of unsorted numbers.
unsorted_list = [3, 1, 4, 5, 9, 2, 6, 5, 3]

# This statement sorts a list of numbers in descending order.
sorted_list = sorted(unsorted_list, reverse=True)

# Displaying a list of sorted elements.
print("Sorted elements in descending order: ")
print(sorted_list)
Output:
       Sorted elements in descending order: 
       [9, 6, 5, 5, 4, 3, 3, 2, 1]

Sorting a List of lists using Lambda Function


Suppose we have a list of lists, and we want to sort it based on a specific element. So, we can achieve this using the lambda function.

Here is a simple example of sorting a list of lists based on the second element of each sublist:

Example 6:

# Creating a list of lists.
list_of_lists = [[3, 6], [1, 4], [2, 8], [4, 9], [5, 7]]

# Sorting a list of lists using lambda function.
sorted_list_of_lists = sorted(list_of_lists, key = lambda x: x[1])

print("Sorted list of lists:")
print(sorted_list_of_lists)
Output:
      Sorted list of lists:
      [[1, 4], [3, 6], [5, 7], [2, 8], [4, 9]]

We can also sort a list of lists using the sort() method with the help of lambda function. Here’s a simple example of it.

Example 7:

# Creating a list of lists.
unsorted_list = [[3, 'Aakash'], [1, 'John'], [4, 'Bob'], [2, 'Mark'], [5, 'Priya']]

# Sort a list of lists based on the first element.
unsorted_list.sort(key = lambda x: x[0])
print(unsorted_list)
Output:
      [[1, 'John'], [2, 'Mark'], [3, 'Aakash'], [4, 'Bob'], [5, 'Priya']]

Sort a List of tuples using Lambda Function


Suppose we have a list of tuples. We can sort it based on a particular element of the tuple using lambda function. Here’s a simple example.

Example 7:

# Creating a list of tuples.
unsorted_list = [(3, 'a'), (1, 'b'), (4, 'c'), (2, 'd'), (5, 'e')]

# Sorting a list of tuples.
sorted_list = sorted(unsorted_list, key = lambda x: x[0])

# Displaying a list of tuple elements.
print("Sorting list of tuple elements in ascending order:")
print(sorted_list)
Output:
      Sorting list of tuple elements in ascending order:
      [(1, 'b'), (2, 'd'), (3, 'a'), (4, 'c'), (5, 'e')]

Similarly, we can also sort a list of tuples using the sort() method with the help of lambda function. You try it yourself.

Sort a List of Dictionaries using Lambda Function


Suppose we have a list of dictionaries that is a collection of dictionaries. In the list, each dictionary represents a single entity or record. For example, consider the following list of dictionaries that represent a list of students and their grades.

students = [
    {"name": "Alice", "grade": 85},
    {"name": "Bob", "grade": 72},
    {"name": "Charlie", "grade": 90},
    {"name": "Dave", "grade": 80},
    {"name": "Eve", "grade": 95},
]

To sort this list of dictionaries based on a specific key, we can use the Python sort() method with a lambda function. Look at the following source code for it.

Example 8:

# Creating a list of dictionaries.
students = [
    {"name": "Alice", "grade": 85},
    {"name": "Bob", "grade": 72},
    {"name": "Charlie", "grade": 90},
    {"name": "Dave", "grade": 80},
    {"name": "Eve", "grade": 95},
]
# Sort a list of dictionaries based on the grade using sort() function.
students.sort(key = lambda x: x["grade"], reverse=True)

# Displaying the list of elements.
print(students)
Output:
       [{'name': 'Eve', 'grade': 95}, 
        {'name': 'Charlie', 'grade': 90}, 
        {'name': 'Alice', 'grade': 85}, 
        {'name': 'Dave', 'grade': 80}, 
        {'name': 'Bob', 'grade': 72}]

In this example, we have used the lambda function that takes an element of the list as input (represented by the x parameter). The lambda function returns the value of the grade key of the dictionary (denoted by x[“grade”]). The sort() method sorts the list of dictionaries based on the returned values in descending order.

How to Sort a List of Complex Objects


To sort a list of complex objects, such as tuples, dictionaries, or objects, we need a key function that defines the sorting criteria. The key function takes an element of the list as input and returns a value based on which the elements have to be sorted.

Let’s take a simple example in which we will sort a list of tuples based on the second element.

Example 9:

# Creating a list of tuples.
students = [("Alice", 22), ("Bob", 19), ("Charlie", 21), ("Dave", 20)]

# Sort a list based on the second element.
def sort_by_age(student):
    return student[1]
students.sort(key = sort_by_age)

# Displaying the list of elements.
print(students)
Output:
      [('Bob', 19), ('Dave', 20), ('Charlie', 21), ('Alice', 22)]

Sort a List based on a Specific Key


To sort a list based on a specific key, we need to use the key parameter in both the sort() and the sorted() functions. The key function takes an element of the list as input and returns a value based on which the elements have to be sorted.

Here is a simple example of sorting a list of string elements based on their length:

Example 10:

# Creating a list of fruits.
fruits = ["banana", "apple", "cherry", "date", "elderberry", "orange"]

# Sort a list based on the length of strings as key.
sorted_fruits = sorted(fruits, key = len)

# Displaying the sorted list of elements.
print(sorted_fruits)
Output:
       ['date', 'apple', 'banana', 'cherry', 'orange', 'elderberry']

We can also sort a list based on multiple keys by providing a tuple of key functions to the sort() or the sorted() function. Let’s take an example in which we will sort a list of tuples based on both the first and the second element. Look at the code below.

Example 11:

# Creating a list of tuples having students and ages.
students = [("Alice", 22), ("Bob", 19), ("Dave", 20), ("Charlie", 21)]

# Sort a list of tuples based on multiple keys.
def sort_by_age_then_name(student):
    return (student[1], student[0])
students.sort(key = sort_by_age_then_name)

# Displaying the list of tuples.
print("Sorting a list of tuples based on multiple keys:")
print(students)
Output:
       Sorting a list of tuples based on multiple keys:
       [('Bob', 19), ('Dave', 20), ('Charlie', 21), ('Alice', 22)]

Google Search FAQs

Q. What is the difference between sorted() and sort() functions?

A: The sorted() function returns a new sorted list, leaving the original list intact, while the sort() function sorts the original list in their place.

Q. Can we sort a list of lists or tuples in Python?

A: Yes, we can sort a list of lists or tuples based on a specific element of the list or tuple using the sorted() or sort() function.

Q. How can we sort a list in descending order in Python?

A: We can pass the reverse=True parameter to the sorted() or the sort() function to sort a list in descending order.

Q. What is the default order for sorting a list in Python?

A: The default order to sort a list in Python is ascending order.

Q. Is sorting a list in Python an efficient operation?

A: Sorting a list in Python can be an expensive operation, especially for large lists. However, Python offers efficient algorithms for sorting that can handle most cases.


In this tutorial, you have learned the different ways to sort a list in Python. You learned how to use the sorted() function and the sort() method to sort a list of elements in ascending or descending order.

You will have also understood how to sort a list of lists, tuples, dictionaries based on a specific element. Hope that you will have understood the basic concepts of all ways to sort a list in Python.
Thanks for reading!!!

The post Sorting List in Python | List Sort, Example appeared first on Scientech Easy.



This post first appeared on Scientech Easy, please read the originial post: here

Share the post

Sorting List in Python | List Sort, Example

×

Subscribe to Scientech Easy

Get updates delivered right to your inbox!

Thank you for your subscription

×