Python sort nested list

Sort Nested List in Python

Generally, sorting a nested list in Python assists in organizing the data and making it easier to process and analyze. You can use this functionality to sort a list of dictionaries with respect to a particular value, sort a nest of tuples based on a specific element of each tuple, or sort a list of lists. Moreover, sorting nested lists also enhances the user experience when the sorted data is presented to the end users.

This blog will cover the following approaches:

Method 1: Sort Nested List in Python Using “sort()” Method

sort()” is a Python built-in method that sorts elements in a nested list in an ascending order automatically. However, it can be utilized for sorting elements in descending order or based on the specified criteria.

Читайте также:  Html input type submit name value

Syntax

To use the “sort()” method in Python, follow the given syntax:

  • List” refers to the list that you want to sort.
  • reverse” is an optional parameter that accepts a “False” boolean value for sorting in ascending order, and “True” for descending order.
  • key” is also another optional parameter used for defining a custom sorting function. Moreover, specifying its value as “None” represents the default sorting order.

Example 1: Sorting List in Ascending Order Using “sort()” Method

First of all, define a function named “Sort()” that accepts the unsorted list as an argument. Then:

  • The “List.sort()” method is invoked on the input list.
  • This method accepts a “key” parameter that specifies a lambda function. This parameter tells the sort() method to utilize the lambda function for getting the sorted list of elements.
  • The lambda function specifies a single argument “l” which refers to each tuple in the list and outputs the second element “l[1]”, representing the first index of the tuple.
  • Note that the lambda function assumes the specified element as sortable.
  • Lastly, the function returns the sorted List as the output:

Next, define a nested list, and pass it to the “Sort()” function:

List = [ [ ‘Zeus’ , 40 ] , [ ‘Raven’ , 20 ] , [ ‘Bumblebee’ , 10 ] , [ ‘Silver Bullet’ , 50 ] ]
print ( Sort ( List ) )

It can be observed that the nested List has been sorted out in ascending order based on the added numeric values:

Method 2: Sort Nested List in Python Using “sorted()” Method

sorted()” Python works pretty similar to the “sort()” method. By default, it also sorts the elements in ascending order. However, the key difference is that the sorted() method can be applied to any iterable, such as dictionaries, or set. Whereas the sort() method does not support this functionality.

Syntax

Check out the following syntax to utilize the “sorted()” method:

Here, “iterable” represent the input sequence you want to sort (a nested List in this case), and “reverse” and “key” are optional parameters as discussed earlier.

Example

Define a function named “Sort()” that accepts “List1” as an argument, and returns the sorted nested List using the “sorted()” method. As “0” is specified as the first index of the tuple, the sorted() method will return the sorted list based on the first element:

Then, create a list with the required elements, and pass it to the “Sort()” method:

List1 = [ [ ‘Zeus’ , 10 ] , [ ‘Raven’ , 20 ] , [ ‘Bumblebee’ , 50 ] , [ ‘Silver Bullet’ , 30 ] ]
print ( Sort ( List1 ) )

As you can see, the nested List has been sorted out alphabetically.

Method 3: Sort Nested List in Python Based on Length

The Python “sort()” method can be also utilized to sort the nested list with respect to length. To do so, specify “len” as the value of the “key” parameter as follows:

Example

Now, create a nested list that comprises further numeric lists. Then, invoke the “sort()” method, and pass “key=len” as arguments. Lastly, call the “print()” function to display the sorted nested Listed on the console:

List1 = [ [ 5 , 10 , 15 , 20 , 25 ] , [ 2 , 4 , 6 ] , [ 10 , 15 , 20 , 25 , 30 , 35 ] ]
List1. sort ( key = len )
print ( List1 )

In this case, the nested List has been sorted out based on the length of the lists (in ascending order):

That was all about sorting nested lists in Python.

Conclusion

For sorting a nested list in Python, use the “sort()” or the “sorted()” method. The sort() follows the “sort(reverse=False, key=None)” syntax. Whereas, to utilize the sorted() method, the “sorted(iterable, reverse=False, key=None)” syntax can be used. Both of these methods can sort a nested list in ascending or descending order or with respect to the index of the tuple. This blog offered different approaches for sorting nesting lists in Python.

About the author

Abdul Mannan

I am curious about technology and writing and exploring it is my passion. I am interested in learning new skills and improving my knowledge and I hold a bachelor’s degree in computer science.

Источник

Sort a List of Lists in Python

Sort a List of Lists in Python

  1. Use the itemgetter() Function From the Operator Module Along With the sorted() Function to Sort a List of Lists in Python
  2. Use the lambda Expression Along With the sorted() Function to Sort a List of Lists in Python
  3. Use the sort() Function to Sort a List of Lists in Python

A list is one of the most powerful data structures used in Python. We can sort a list in Python by arranging all its elements in ascending or descending order based on the requirement.

We can also have nested lists in Python. These can be thought of as a list of lists. Sorting a list of lists arranges all the inner lists according to the specified index as the key.

In this tutorial, we will sort a list of lists in Python based on some indexes.

Use the itemgetter() Function From the Operator Module Along With the sorted() Function to Sort a List of Lists in Python

The function sorted() is used to sort a list in Python. By default, it sorts the list in ascending order. The function itemgetter() from the operator module takes an index number as a parameter and returns the element from the data set placed at that index number.

Therefore, the function sorted(List_name, key=itemgetter(index_number)) sorts a list of lists by the element positioned at the specified index_number of each inner list.

from operator import itemgetter A = [[10, 8], [90, 2], [45, 6]] print("Sorted List A based on index 0: % s" % (sorted(A, key=itemgetter(0)))) B = [[50, 'Yes'], [20, 'No'], [100, 'Maybe']] print("Sorted List B based on index 1: % s" % (sorted(B, key=itemgetter(1)))) 
Sorted List A based on index 0: [[10, 8], [45, 6], [90, 2]] Sorted List B based on index 1: [[100, 'Maybe'], [20, 'No'], [50, 'Yes']] 

To sort a list of lists in descending order, the reverse parameter is used along with the key parameter, and the list name in the sorted() function.

from operator import itemgetter C = [[10, 8, 'Cat'], [90, 2, 'Dog'], [45, 6, 'Bird']] print("Reversed sorted List C based on index 1: % s" % (sorted(C, key=itemgetter(1), reverse=True))) 
Reverse sorted List C based on index 1: [[10, 8, 'Cat'], [45, 6, 'Bird'], [90, 2, 'Dog']] 

Источник

Sort a List of Lists in Python

Sort a List of Lists in Python

  1. Use the itemgetter() Function From the Operator Module Along With the sorted() Function to Sort a List of Lists in Python
  2. Use the lambda Expression Along With the sorted() Function to Sort a List of Lists in Python
  3. Use the sort() Function to Sort a List of Lists in Python

A list is one of the most powerful data structures used in Python. We can sort a list in Python by arranging all its elements in ascending or descending order based on the requirement.

We can also have nested lists in Python. These can be thought of as a list of lists. Sorting a list of lists arranges all the inner lists according to the specified index as the key.

In this tutorial, we will sort a list of lists in Python based on some indexes.

Use the itemgetter() Function From the Operator Module Along With the sorted() Function to Sort a List of Lists in Python

The function sorted() is used to sort a list in Python. By default, it sorts the list in ascending order. The function itemgetter() from the operator module takes an index number as a parameter and returns the element from the data set placed at that index number.

Therefore, the function sorted(List_name, key=itemgetter(index_number)) sorts a list of lists by the element positioned at the specified index_number of each inner list.

from operator import itemgetter A = [[10, 8], [90, 2], [45, 6]] print("Sorted List A based on index 0: % s" % (sorted(A, key=itemgetter(0)))) B = [[50, 'Yes'], [20, 'No'], [100, 'Maybe']] print("Sorted List B based on index 1: % s" % (sorted(B, key=itemgetter(1)))) 
Sorted List A based on index 0: [[10, 8], [45, 6], [90, 2]] Sorted List B based on index 1: [[100, 'Maybe'], [20, 'No'], [50, 'Yes']] 

To sort a list of lists in descending order, the reverse parameter is used along with the key parameter, and the list name in the sorted() function.

from operator import itemgetter C = [[10, 8, 'Cat'], [90, 2, 'Dog'], [45, 6, 'Bird']] print("Reversed sorted List C based on index 1: % s" % (sorted(C, key=itemgetter(1), reverse=True))) 
Reverse sorted List C based on index 1: [[10, 8, 'Cat'], [45, 6, 'Bird'], [90, 2, 'Dog']] 

Use the lambda Expression Along With the sorted() Function to Sort a List of Lists in Python

The lambda expressions are simple one-line functions in Python.

The function sorted(List_name, key=lambda x:x[index_number]) is used to sort a list of lists by the element positioned at the specified index_number of each inner list.

A = [[100, 'Yes'], [40, 'Maybe'], [60, 'No']] print("Sorted List A based on index 0: % s" % (sorted(A, key=lambda x:x[0]))) B = [[2, 'Dog'], [0, 'Bird'], [7, 'Cat']] print("Sorted List A based on index 1: % s" % (sorted(B, key=lambda x:x[1]))) 
Sorted List A based on index 0: [[40, 'Maybe'], [60, 'No'], [100, 'Yes']] Sorted List B based on index 1: [[0, 'Bird'], [7, 'Cat'], [2, 'Dog']] 

Similarly, we can use the reverse parameter to get the output in descending order.

C = [[60, 5], [90, 7], [30, 10]] print("Reversed sorted List C based on index 0: % s" % (sorted(C, key=lambda x:x[0], reverse=True))) 
Reversed sorted List C based on index 0: [[90, 7], [60, 5], [30, 10]] 

Use the sort() Function to Sort a List of Lists in Python

The sort() method sorts the list of lists in Python according to the first element of each inner list. This method makes changes in the original list itself. We use the reverse parameter to sort in descending order.

A = [[55, 90], [45, 89], [90, 70]] A.sort() print("New sorted list A is % s" % (A)) A.sort(reverse=True) print("New reverse sorted list A is % s" % (A)) 
New sorted list A is [[45, 89], [55, 90], [90, 70]] New reverse sorted list A is [[90, 70], [55, 90], [45, 89]] 

To sort the given list according to the length of the inner lists, key=len parameter is used.

A = [[5, 90, 'Hi', 66], [80, 99], [56, 32, 80]] A.sort(key=len) print("New sorted list A is % s" % (A)) 
New sorted list A is [[80, 99], [56, 32, 80], [5, 90, 'Hi', 66]] 

Related Article — Python List

Copyright © 2023. All right reserved

Источник

Оцените статью