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

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!