How to sort a List using Lambda in Python



Example:

>>> numbers = [4 ,9, 11, 3, 7, 1, 8, 2]
>>> sorted_numbers_lambda = sorted(numbers, key=lambda x: x % 3)
>>> print(sorted_numbers_lambda)

[9, 3, 4, 7, 1, 11, 8, 2] 

We have made use of the lambda function to do a custom sort of the list, here x: x % 3 is used as the key for sorting the numbers based on their remainder when divided by 3.

Sorting a List using Lambda in Python

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap