Sorting Tuples Using Lambda

Write a Python program that uses a lambda function to sort a list of tuples based on the second element in each tuple. The function should return the sorted list.

Example 1:

Input: [('a', 2), ('b', 1), ('c', 3)] 
Output: [('b', 1), ('a', 2), ('c', 3)]

Example 2:

Input: [('x', 10), ('y', 5), ('z', 20)] 
Output: [('y', 5), ('x', 10), ('z', 20)]

Use a lambda function as the key in the sorted function to sort the list based on the second element of each tuple.

# Define the list of tuples
tuples_list = [('a', 2), ('b', 1), ('c', 3)]

# Use a lambda function to sort the list
sorted_list = sorted(tuples_list, key=lambda x: x[1])

print(sorted_list) # Output: [('b', 1), ('a', 2), ('c', 3)]

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!