Open In App

Python Program to Sort the list according to the column using lambda

Last Updated : 25 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list, the task is to sort the list according to the column using the lambda approach. Examples:

Input : array = [[1, 3, 3], [2, 1, 2], [3, 2, 1]] Output : Sorted array specific to column 0, [[1, 3, 3], [2, 1, 2], [3, 2, 1]] Sorted array specific to column 1, [[2, 1, 2], [3, 2, 1], [1, 3, 3]] Sorted array specific to column 2, [[3, 2, 1], [2, 1, 2], [1, 3, 3]] Input : array = [[‘java’, 1995], [‘c++’, 1983], [‘python’, 1989]] Output : Sorted array specific to column 0, [[‘c++’, 1983], [‘java’, 1995], [‘python’, 1989]] Sorted array specific to column 1, [[‘c++’, 1983], [‘python’, 1989], [‘java’, 1995]]

Approach:

  • sorted() built-in function in Python gives a new sorted list from an iterable.
  • key parameter to specify a function to be called on each list element prior to making comparisons.
  • lambda is used as a function to iterate on each element.
  • key = lambda x:x[i] here i is the column on which respect to sort the whole list.

Below is the implementation. 

Python3




# Python code to sorting list
# according to the column
 
# sortarray function is defined
def sortarray(array):
     
    for i in range(len(array[0])):
         
        # sorting array in ascending
        # order specific to column i,
        # here i is the column index
        sortedcolumn = sorted(array, key = lambda x:x[i])
         
        # After sorting array Column 1
        print("Sorted array specific to column {}, \
        {}".format(i, sortedcolumn))
     
# Driver code
if __name__ == '__main__':
     
    # array of size 3 X 2
    array = [['java', 1995], ['c++', 1983],
             ['python', 1989]]
     
    # passing array in sortarray function
    sortarray(array)


Output:

Sorted array specific to column 0, [[‘c++’, 1983], [‘java’, 1995], [‘python’, 1989]] Sorted array specific to column 1, [[‘c++’, 1983], [‘python’, 1989], [‘java’, 1995]]

Time complexity: O(n*logn), as sorting is done.
Auxiliary Space: O(n),where n is length of array.


Similar Reads

Ways to sort list of dictionaries by values in Python - Using lambda function
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
2 min read
Python | Sort list according to other list order
Sorting is an essential utility used in majority of programming, be it for competitive programming or development. Conventional sorting has been dealt earlier many times. This particular article deals with sorting with respect to some other list elements. Let's discuss certain ways to sort list according to other list order. Method #1 : Using List
5 min read
Python | Sort a List according to the Length of the Elements
In this program, we need to accept a list and sort it based on the length of the elements present within. Examples: Input : list = ["rohan", "amy", "sapna", "muhammad", "aakash", "raunak", "chinmoy"] Output : ['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad'] Input : list = [["ram", "mohan", "aman"], ["gaurav"], ["amy", "sima", "a
4 min read
Python | Sort a list according to the second element in sublist
In this article, we will learn how to sort any list, according to the second element of the sublist present within the main list. We will see two methods of doing this. We will learn three methods of performing this sort. One by the use of Bubble Sort, the second by using the sort() method, and last but not the least by the use of the sorted() meth
9 min read
Python - Sort list of Single Item dictionaries according to custom ordering
Given single item dictionaries list and keys ordering list, perform sort of dictionary according to custom keys. Input : test_list1 = [{'is' : 4}, {"Gfg" : 10}, {"Best" : 1}], test_list2 = ["Gfg", "is", "Best"] Output : [{'Gfg': 10}, {'is': 4}, {'Best': 1}] Explanation : By list ordering, dictionaries list get sorted. Input : test_list1 = [{"Gfg" :
4 min read
Python Program to Sort Matrix Rows According to Primary and Secondary Indices
Given Matrix, the task here is to write a Python program to sort rows based on primary and secondary indices. First using primary indices the rows will be arranged based on the element each row has at the specified primary index. Now if two rows have the same element at the given primary index, sorting will be performed again using secondary index.
3 min read
Python Program Maximum of Three Number using Lambda
Here we will create a lambda function to find the maximum among three numbers in Python. Example: Input: a=10, b=24, c=15Output: 24 # using LambdaFinding Maximum Among Three Numbers in PythonBelow are some of the ways by which we can find the maximum among three numbers in Python. Using lambda with max() FunctionUsing lambda with nested if-else blo
3 min read
Difference between List comprehension and Lambda in Python
List comprehension is an elegant way to define and create a list in Python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. A list comprehension generally consists of these parts : Output expression,Input sequence,A variable representing a member of the input sequence
3 min read
Python - Lambda Function to Check if value is in a List
Given a list, the task is to write a Python program to check if the value exists in the list or not using the lambda function. Example: Input : L = [1, 2, 3, 4, 5] element = 4 Output : Element is Present in the list Input : L = [1, 2, 3, 4, 5] element = 8 Output : Element is NOT Present in the list We can achieve the above functionality using the f
2 min read
Python | Reshape a list according to given multi list
Given two lists, a single dimensional and a multidimensional list, write Python program to reshape the single dimensional list according to the length of multidimensional list. Examples: Input : list1 = [[1], [2, 3], [4, 5, 6]] list2 = ['a', 'b', 'c', 'd', 'e', 'f'] Output : [['a'], ['b', 'c'], ['d', 'e', 'f']] Input : list1 = [[8, 2, 5], [1], [12,
7 min read
Practice Tags :