TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: How to Sort with Lambda in Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python ExamplesPython Tutorials

How to Sort with Lambda in Python

Last updated: Jun 02, 2024 11:55 am
By Soumya Agarwal
Share
10 Min Read
Python Sort Using Lambda With Examples
SHARE

Sorting is a common operation in programming, and Python provides powerful tools to make it efficient and flexible. In this tutorial, we will focus on sorting using lambda functions in Python. Ther also known as anonymous functions, are concise and convenient for one-time use, making them a perfect fit for sorting tasks. By the end of this tutorial, you’ll have a solid understanding of how to use lambda functions in various scenarios.

Contents
Sorting ListMethod 1: Using the sorted() function with LambdaMethod 2: Using the sort() method with LambdaSorting StringsMethod 1: Using the sorted() function with LambdaMethod 2: Using the sort() method with LambdaSorting Dictionaries with LambdaMethod 1: Sorting by KeysMethod 2: Sorting by ValuesMethod 3: Sorting by Values in Descending OrderSorting Custom Objects with LambdaSorting by Story PointsSorting by Owner’s Name LengthFAQs: Sorting with Lambda in PythonQ1: Can I sort a list of strings in reverse alphabetical order using lambda?Q2: How can I sort a list of tuples based on the second element using lambda?Q3: Can I sort a dictionary by values in descending order using lambda?Q4: Is it possible to sort a list of custom objects based on a specific attribute using lambda?Q5: Are lambda functions the only way to sort data in Python?

Understanding Lambda Functions

Before we dive into sorting, let’s briefly understand lambda functions. In Python, a lambda function is a small anonymous function defined with the lambda keyword. It can take any number of arguments but can only have one expression. The syntax is simple:

# Example of a lambda function
add = lambda x, y: x + y
print(add(3, 5))  # Output: 8

Lambda functions are often used for short and simple operations. From our experience, we feel they are super handy when sorting data.

Sorting List

Let’s start by sorting a list of numbers using a lambda function. Suppose we have the following list:

nums = [4, 2, 7, 1, 9]

Method 1: Using the sorted() function with Lambda

The sorted() function allows us to use a lambda function as the sorting key. For example, let’s sort the list of numbers in descending order:

sorted_num_desc = sorted(nums, key=lambda x: x, reverse=True)
print(sorted_num_desc)  # Output: [9, 7, 4, 2, 1]

Here, the lambda function lambda x: x is equivalent to the identity function, meaning it returns the number itself. The key parameter is optional in this case, but it’s useful for custom sorting criteria.

Method 2: Using the sort() method with Lambda

If you want to sort the list in place, you can use the sort() method of the list:

nums.sort(key=lambda x: x, reverse=True)
print(nums)  # Output: [9, 7, 4, 2, 1]

This modifies the original list and sorts it in descending order using the lambda function.

Sorting Strings

Now, let’s move on to sorting a list of strings. Suppose we have the following list of names:

names = ['Alice', 'Bob', 'Charlie', 'David', 'Eva']

Method 1: Using the sorted() function with Lambda

Let’s sort the list of names based on their lengths in ascending order:

sorted_names_len = sorted(names, key=lambda x: len(x))
print(sorted_names_len)  # Output: ['Bob', 'Eva', 'Alice', 'David', 'Charlie']

Here, the function lambda x: len(x) returns the length of each name, and the list is sorted based on these lengths.

Method 2: Using the sort() method with Lambda

Similarly, we can use the sort() method to sort the list in place:

names.sort(key=lambda x: len(x))
print(names)  # Output: ['Bob', 'Eva', 'Alice', 'David', 'Charlie']

This modifies the original list and sorts it based on the lengths of the names.

Sorting Dictionaries with Lambda

Sorting dictionaries can be a bit more complex because we need to decide whether to sort by keys or values. Let’s explore both scenarios.

Suppose we have the following dictionary of ages:

ages = {'Alice': 25, 'Bob': 30, 'Charlie': 22, 'David': 28, 'Eva': 35}

Method 1: Sorting by Keys

Let’s sort the dictionary by keys in ascending order:

sorted_ages_keys = sorted(ages.items(), key=lambda x: x[0])
print(dict(sorted_ages_keys))
# Output: {'Alice': 25, 'Bob': 30, 'Charlie': 22, 'David': 28, 'Eva': 35}

Here, ages.items() returns a list of key-value pairs, and the function lambda x: x[0] extracts and sorts based on the keys.

Method 2: Sorting by Values

Now, let’s sort the dictionary by values in ascending order:

sorted_ages_val = sorted(ages.items(), key=lambda x: x[1])
print(dict(sorted_ages_val))
# Output: {'Charlie': 22, 'Alice': 25, 'David': 28, 'Bob': 30, 'Eva': 35}

In this case, the function lambda x: x[1] extracts and sorts based on the values.

Method 3: Sorting by Values in Descending Order

If we want to sort by values in descending order, we can use the reverse parameter:

sorted_ages_val_desc = sorted(ages.items(), key=lambda x: x[1], reverse=True)
print(dict(sorted_ages_val_desc))
# Output: {'Eva': 35, 'Bob': 30, 'David': 28, 'Alice': 25, 'Charlie': 22}

Here, the reverse=True parameter sorts the dictionary by values in descending order.

Sorting Custom Objects with Lambda

You can also use lambda functions to sort lists of custom objects. Let’s say we have a list of simple objects representing agile user stories:

class Story:
    def __init__(self, desc, owner, points):
        self.desc = desc
        self.owner = owner
        self.points = points

# Creating a list of Story objects
stories = [
    Story('Add a button', 'Eric Matthes', 15),
    Story('Log message', 'Robert C. Martin', 8),
    Story('Create a form', 'Andrew Hunt, David Thomas', 5),
    Story('Support Unicode', 'Erich, Richard, Ralph, John', 11)
]

Sorting by Story Points

Let’s sort the list of stories based on the number of points:

sorted_story_by_pts = sorted(stories, key=lambda x: x.points)
for st in sorted_story_by_pts:
    print(f"The story '{st.desc}' was created by {st.owner} with {st.points} points")

This sorts the list of books based on the pages attribute of each book.

Sorting by Owner’s Name Length

Now, let’s sort the stories based on the length of the owner’s name:

sorted_story_by_len = sorted(stories, key=lambda x: len(x.owner))
for st in sorted_story_by_len:
    print(f"{st.desc} by {st.owner}, {st.points} points")

Here, the function lambda x: len(x.owner) sorts the books based on the length of the owner’s name.

FAQs: Sorting with Lambda in Python

Q1: Can I sort a list of strings in reverse alphabetical order using lambda?

Answer: Yes, you can sort a list of strings in reverse alphabetical order using the sorted() function with a lambda function. For example:

strings = ['apple', 'banana', 'orange', 'kiwi']
sorted_str_rev_alpha = sorted(strings, key=lambda x: x, reverse=True)
print(sorted_str_rev_alpha)
# Output: ['orange', 'kiwi', 'banana', 'apple']

Q2: How can I sort a list of tuples based on the second element using lambda?

Answer: You can sort a list of tuples based on the second element using the sorted() function with a lambda function. Here’s an example:

tup_list = [(2, 5), (1, 8), (3, 3), (4, 1)]
sorted_tup_second_ele = sorted(tup_list, key=lambda x: x[1])
print(sorted_tup_second_ele)
# Output: [(4, 1), (3, 3), (2, 5), (1, 8)]

Q3: Can I sort a dictionary by values in descending order using lambda?

Answer: Yes, you can sort a dictionary by values in descending order using the sorted() function with a lambda function. Here’s an example:

ages = {'Alice': 25, 'Bob': 30, 'Charlie': 22, 'David': 28, 'Eva': 35}
sorted_ages_val_desc = sorted(ages.items(), key=lambda x: x[1], reverse=True)
print(dict(sorted_ages_val_desc))
# Output: {'Eva': 35, 'Bob': 30, 'David': 28, 'Alice': 25, 'Charlie': 22}

Q4: Is it possible to sort a list of custom objects based on a specific attribute using lambda?

Answer: Yes, you can sort a list of custom objects based on a specific attribute using the sorted() function with a lambda function. Here’s an example using a list of Book objects:

class Story:
    def __init__(self, desc, owner, points):
        self.desc = desc
        self.owner = owner
        self.points = points

# Creating a list of Story objects
stories = [
    Story('Add a button', 'Eric Matthes', 15),
    Story('Log message', 'Robert C. Martin', 8),
    Story('Create a form', 'Andrew Hunt, David Thomas', 5),
    Story('Support Unicode', 'Erich, Richard, Ralph, John', 11)
]

sorted_story_by_pts = sorted(stories, key=lambda x: x.points)
for st in sorted_story_by_pts:
    print(f"The story '{st.desc}' was created by {st.owner} with {st.points} points")

Q5: Are lambda functions the only way to sort data in Python?

Answer: No, lambda functions are not the only way to sort data in Python. You can use regular functions, methods, or even custom classes with the key parameter of the sorted() function or the sort() method. Lambda functions are convenient for short and one-time operations. However, you can take other approaches as per the use case.

Must Read:
1. Python Sorting a Dictionary
2. Python Dictionary to JSON
3. Python Append to Dictionary
4. Python Merge Dictionaries
5. Python Iterate Through a Dictionary
6. Python Search Keys by Value in a Dictionary
7. Python Multiple Ways to Loop Through a Dictionary
8. Python Insert a Key-Value Pair to the Dictionary

You’ve explored various ways to sort data using lambda functions in Python. Now, experiment with examples provided for each method. Modify them to suit your needs and incorporate lambda functions into your programming toolkit.

Lastly, our site needs your support to remain free. Share this post on social media (Facebook/Twitter) if you gained some knowledge from this tutorial.

Happy Coding,
Team TechBeamers

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Soumya Agarwal Avatar
By Soumya Agarwal
Follow:
I'm a BTech graduate from IIITM Gwalior. I have been actively working with large MNCs like ZS and Amazon. My development skills include Android and Python programming, while I keep learning new technologies like data science, AI, and LLMs. I have authored many articles and published them online. I frequently write on Python programming, Android, and popular tech topics. I wish my tutorials are new and useful for you.
Previous Article Python Sort Array Values With Examples Python Sort Array Values With Examples
Next Article Python Sort List of Strings With Examples Python Sort List of Strings With Examples

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x