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.

**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

## TOC – Python Sort Using Lambdas

- Understanding Lambda Functions
- Sorting List
- Sorting Strings
- Sorting Dictionaries with Lambda
- Sorting Custom Objects with Lambda
- FAQs: Sorting with Lambda in Python
- Q1: 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?

- Conclusion

### 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, simple operations, and they are especially 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, one-time operations, but you have the flexibility to use other approaches based on your specific needs.

## Conclusion

You’ve now explored various ways to sort data using lambda functions in Python. Lambda functions are powerful tools for concise and on-the-fly operations, and they fit seamlessly into Python’s sorting functions. Whether you’re sorting Python numbers, strings, dictionaries, or custom objects, lambda functions provide a flexible and efficient solution.

Experiment with these examples, modify them to suit your specific needs and incorporate lambda functions into your programming toolkit.

**Happy Coding,Team TechBeamers**