Python Program to Sort a List of Tuples Using Lambda

1. Introduction

In Python, tuples are often used to store related pieces of information. Sorting a list of such tuples based on one or more elements can be efficiently accomplished using lambda functions, which provide a quick and easy way to specify a sorting key inline.

Definition

A lambda function in Python is a small anonymous function that can take any number of arguments but can only have one expression. When sorting a list of tuples, a lambda function is often used as the key to specify which element in the tuples to sort by.

2. Program Steps

1. Define a list of tuples.

2. Use the sorted() function and pass a lambda function to the key argument to sort the tuples by a specified element.

3. Print the sorted list of tuples.

3. Code Program

# Step 1: Define a list of tuples
tuple_list = [(1, 'one'), (3, 'three'), (2, 'two'), (4, 'four')]

# Step 2: Use sorted() with a lambda function to sort by the first element of each tuple
sorted_by_first = sorted(tuple_list, key=lambda x: x[0])

# Step 3: Print the list sorted by the first element
print(f"List sorted by the first element: {sorted_by_first}")

# Use sorted() with a lambda function to sort by the second element of each tuple
sorted_by_second = sorted(tuple_list, key=lambda x: x[1])

# Print the list sorted by the second element
print(f"List sorted by the second element: {sorted_by_second}")

Output:

List sorted by the first element: [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
List sorted by the second element: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

Explanation:

1. tuple_list is created with four tuples, each containing a number and its corresponding word.

2. sorted_by_first uses the sorted() function with a lambda function as the key. The lambda x: x[0] indicates that sorting is based on the first element of each tuple.

3. The first print statement outputs tuple_list sorted by the first element in each tuple, showing them in ascending numerical order.

4. sorted_by_second is also sorted using a lambda function as the key, but this time it's lambda x: x[1], which sorts by the second element (the string) of each tuple.

5. The second print statement shows tuple_list sorted alphabetically by the second element.

Comments