• Post author:
  • Post category:Python
  • Post last modified:March 27, 2024
  • Reading time:14 mins read
You are currently viewing Sort using Lambda in Python

How to perform a sort with lambda in python? A lambda function is a small anonymous function, it can be created or defined using the lambda keyword. You can use lambda as the key function when sorting a list. for example, use key=lambda to the sort() function to order list.

Advertisements

A Python lambda is used to execute an anonymous function. This function can take any number of arguments, but can only have one expression and they can be used wherever function objects are required.

1. Quick Examples of Sort Using Lambda

If you are in a hurry, below are some quick examples of how to sort the list elements by using the Python lambda function.


# Quick examples of sort using lambda

# Create list with numbers
numbers = [2, 4, 1, 6, 3]

# Example 1: Using sort() with lambda
numbers.sort(key=lambda x:x)

# Example 2: Using sorted() with lambda
sorted_numbers = sorted(numbers, key=lambda x: x)

# Example 3: Using sort() with lambda
numbers.sort(key=lambda x:x, reverse=True)

# Example 4: Using sorted() with lambda
sorted_numbers = sorted(numbers, key=lambda x: x, reverse=True)

# Example 5: Sort list of tuples
lst = [('Ann','20','400'), ('Scott','40','500'), ('Bean','10','450')]
lst.sort(key=lambda x:x[1])

2. Syntax of sort()

Following is the syntax of the python sort() and sorted() functions using lambda as key.


# syntax of sort()
list.sort(key=lambda, reverse)

# syntax of sorted()
sorted(iterable,key=lambda, reverse)

2.1 Parameters of sort()

Following are the parameters of the

  • key – A function that takes an element of the list as input and, a function to specify the sorting criteria(s).
  • reverse – A boolean value specifies whether the list should be sorted in ascending (False) or descending (True) order. The default is reverse=False.

2. Python list.sort() with Lambda

By using the list.sort() function you can order a list of numbers in ascending or descending order and use key=lambda to specify the sort function as python lambda, it also takes reverse param which is a boolean value that specifies whether the list should be sorted in ascending (False) or descending (True) order. The default is reverse=False.

The key function is an optional parameter that can be used to specify how the items should be sorted. When you use key=lambda, The lambda function is applied to each item in the list, and the resulting values are used to determine the sort order.


# Create list with numbers
numbers = [2, 4, 1, 6, 3]
print("Original list:",numbers)

# Using sort() with lambda
numbers.sort(key=lambda x:x)
print("Sorted:",numbers)

Yields below output.

python sort lambda

3. Python sorted() with Lambda

Alternatively, the sorted() function in Python is used to sort a sequence (such as a list, or tuple) of numbers in ascending order. The function returns a new sorted list, leaving the original sequence unchanged. Similar to the above method, use the key=lambda to specify the sort function.


# Create list with numbers
numbers = [2, 4, 1, 6, 3]
print("Original list:",numbers)

# Using sorted() with lambda
sorted_numbers = sorted(numbers, key=lambda x: x)
print("Sorted:",sorted_numbers)

Yields below output.


# Output:
Original list: [2, 4, 1, 6, 3]
Sorted: [1, 2, 3, 4, 6]

4. Sort Reverse Order Using Lambda

Use reverse=True and key=lambda as params to the list.sort() or sorted() functions to order the elements in descending or reverse order. I have a dedicated article on sorting in reverse order in Python.


# Create list with numbers
numbers = [2, 4, 1, 6, 3]
print("Original list:",numbers)

# Using sort() with lambda
numbers.sort(key=lambda x:x, reverse=True)
print("Revers order using sort:",numbers)

# Using sorted() with lambda
sorted_numbers = sorted(numbers, key=lambda x: x, reverse=True)
print("Revers order using sorted:",sorted_numbers)

Yields below output.


# Output:
Original list: [2, 4, 1, 6, 3]
Revers order using sort: [6, 4, 3, 2, 1]
Revers order using sorted: [6, 4, 3, 2, 1]

5. Sorting List of Tuples Using Lambda

Finally, let’s sort the list of tuples using the lambda function. Here, you need to select the index on which you wanted to select. x[1] means sort on second position.


# Sort list of tuples
lst = [('Ann','20','400'), ('Scott','40','500'), ('Bean','10','450')]
lst.sort(key=lambda x:x[1])
print(lst)

Yields below output.


# Output:
# [('Bean', '10', '450'), ('Ann', '20', '400'), ('Scott', '40', '500')]

Frequently Asked Questions

What is the purpose of using lambda in sorting in Python?

In Python, the sorted function allows custom sorting based on a specific criterion defined by the key parameter. Lambda functions are often used in conjunction with sorted to create concise and temporary functions for sorting purposes. Lambda functions are anonymous functions that can be defined inline, making them convenient for short-lived tasks like sorting.

How does the key parameter work in the sorted function with lambda?

The key parameter in the sorted function is used to specify a function that takes an element as input and returns a value based on which the sorting is performed. Lambda functions are commonly employed as the key function. For instance, key=lambda x: x indicates that the sorting should be based on the elements themselves. Adjust the lambda function to customize the sorting criteria.

Can I sort a list in descending order using lambda?

You can sort a list in descending order by setting the reverse parameter to True in the sorted function.

Are lambda functions the only way to customize sorting in Python?

Lambda functions are not the only way. You can also use regular functions by defining a named function and passing it as the key parameter. Lambda functions are often preferred for short, one-time use cases, while named functions are more suitable for complex or reusable sorting criteria.

Can I use lambda functions with other functions besides sorted for custom operations?

Lambda functions can be used with various functions in Python, not just sorted. They are commonly employed in functions like map, filter, and reduce as well, providing a concise way to define small, one-time-use functions inline.

What happens if I omit the key parameter when using lambda with sorted?

If you omit the key parameter, the sorted function will perform a default sorting based on the natural order of the elements. In the case of strings, it will be alphabetical; for numbers, it will be in ascending order.

Conclusion

In this article, you have learned how to sort the list elements by using the Python lambda function. For example, you can use the lambda as the key function when sorting a list (key=lambda). Use this either with the sort() or sorted() function to order iterable like list, tuple using lambda.

References

Naveen

Naveen (NNK) is a Data Engineer with 20+ years of experience in transforming data into actionable insights. Over the years, He has honed his expertise in designing, implementing, and maintaining data pipelines with frameworks like Apache Spark, PySpark, Pandas, R, Hive and Machine Learning. Naveen journey in the field of data engineering has been a continuous learning, innovation, and a strong commitment to data integrity. In this blog, he shares his experiences with the data as he come across. Follow Naveen @ LinkedIn LinkedIn