+

Python | Sort the list of lists by lexicographic meaning and then by length

Method # 1: Using sort () twice
The first approach that comes to mind is — this is a general way to use the sort function twice, first based on value and then based on the size of the list.

# Python code for demonstration
# sort the list of lists by value and length
# using sort () twice

 
# initializing list

test_list = [[[ 1 , 4 , 3 , 2 ], [ 5 , 4 , 1 ], [ 1 , 4 , 6 , 7 ]]

 
# print original list

print ( "The original list is:" + str (test_list))

 
# using sort () twice
# sorting the list of lists by value and length
test_list.sort ()

test_list.sort (key = l en )

 
# print result

print ( "The list after sorting by value and length " + str (test_list))

Exit:

The original list is: [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]]
The list after sorting by value and length [[5, 4, 1], [1, 4, 3, 2], [1, 4, 6, 7]]

Method # 2: Using a lambda function
The above method calls the same sort function twice, but as an improvement, this method calls the sort function only once and uses a lambda function to do both sorts in one go.

 

# Python code for demonstration
# sort the list of lists by value and length
# using lambda function

 
# initializing list

test_list = [[ 1 , 4 , 3 , 2 ], [ 5 , 4 , 1 ], [ 1 , 4 , 6 < code class = "plain">, 7 ]]

 
# print original list

print ( "The original list is:" + str (test_list))

  
# using the lambda function
# sorting the list of lists by value and length

res = sorted (test_list, key = lambda i: ( len (i), i))

 
# print result

print ( "The list after sorting by value and length" + str (res))

Output:

The original list is: [[1, 4, 3, 2], [5, 4, 1], [1, 4, 6, 7]]
The list after sorting by value and length [[5, 4, 1], [1, 4, 3, 2], [1, 4, 6, 7]]

Get Solution for free from DataCamp guru