• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / Sorting with Lambda Functions in Python

Sorting with Lambda Functions in Python

March 12, 2022 Leave a Comment

In Python, we can use a lambda expression with the sorted() or sort() function to sort with a function. To use lambda with sorted(), pass the lambda expression to the ‘key’ argument.

lst = ["this","is","another","list","of","strings"]

list_sorted_by_second_letter = sorted(lst,key=lambda x: x[1])

print(list_sorted_by_second_letter) 

#output:
['of', 'this', 'list', 'another', 'is', 'strings']

You can do the same for the sort() function, which sorts a list in place.

lst = ["this","is","another","list","of","strings"]

lst.sort(key=lambda x: x[1])

print(lst) 

#output:
['of', 'this', 'list', 'another', 'is', 'strings']

In Python, lambda expressions are very useful for creating anonymous functions which can be applied on variables or collections of objects.

We can use lambda expressions when sorting a list using the sorted() or sort() functions. The lambda expression will tell the sorting algorithm which values to use to sort the list.

For example, we can sort a list of strings by the second character using a lambda expression.

To use lambda with sorted() or sort(), pass the lambda expression to the ‘key’ argument.

Below is a simple example of how to sort a list of strings by the second character in Python using a lambda expression.

lst = ["this","is","another","list","of","strings"]

list_sorted_by_second_letter = sorted(lst, key=lambda x: x[1])

print(list_sorted_by_second_letter) 

#output:
['of', 'this', 'list', 'another', 'is', 'strings']

Another example is sorting a list of strings which are made up of integers.

To sort the list of strings made up of integers, we can pass “key=int” to the sort() function. The following code will sort a list of strings made up of integers:

l = ["100","12","34","1","5","56","78"]

l.sort(key=int)

print(l) 

#output:
["1","5","12","34","56","78","100"]

Sorting a List of Objects with lambda in Python

Another example where the use of a lambda makes sense is when sorting a list of objects.

For example, you can sort a list of tuples by the second element easily with a lambda.

Below is how to sort a list of tuples by the second element in Python with the sorted() function and a lambda expression.

list_of_tuples = [('apple', 3), ('pear', 5), ('banana', 1), ('lime', 4)]

sorted_list = sorted(list_of_tuples, key=lambda t: t[1])

print(sorted_list)

#Output:
[('banana', 1), ('apple', 3), ('lime', 4), ('pear', 5)]

Sorting by Two Keys with lambda in Python

One such situation where we need to do a little more work to get the result we want is if we want to sort our data by two keys.

To sort a list of objects by two keys in Python, the easiest way is with the key parameter and a tuple of the keys you want to sort by.

Just pass the keys you want to sort by as a tuple for your sorting lambda expression.

Below is a simple example showing you how to sort a list of dictionaries by two keys in Python.

list_of_dicts = [{"name":"Bob","weight":100,"height":50},
{"name":"Sally","weight":120,"height":70},
{"name":"Jim","weight":120,"height":60},
{"name":"Larry","weight":150,"height":60}]

list_of_dicts.sort(key= lambda x: (x["weight"],x["name"]))

print(list_of_dicts)

#Output:
[{'name': 'Bob', 'weight': 100, 'height': 50}, {'name': 'Jim', 'weight': 120, 'height': 60}, {'name': 'Sally', 'weight': 120, 'height': 70}, {'name': 'Larry', 'weight': 150, 'height': 60}

Hopefully this article has been useful for you to learn how to sort with a lambda expression in Python.

Other Articles You'll Also Like:

  • 1.  Using Python to Remove Duplicates from List
  • 2.  Golden Ratio Constant phi in Python
  • 3.  How to Count Vowels in a String Using Python
  • 4.  Drop Last n Rows of pandas DataFrame
  • 5.  Python ljust Function – Left Justify String Variable
  • 6.  Python divmod() Function – Get Quotient and Remainder After Division
  • 7.  How to Remove NaN from List in Python
  • 8.  Python Delete Variable – How to Delete Variables with del Keyword
  • 9.  Python isfinite() Function – Check if Number is Finite with math.isfinite()
  • 10.  Get Username in Python using os module

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy