w3resource

Python: Sort a list of tuples using Lambda

Python Lambda: Exercise-3 with Solution

Write a Python program to sort a list of tuples using Lambda.

Sample Solution:

Python Code :

# Create a list of tuples named 'subject_marks', each tuple containing a subject and its corresponding marks
subject_marks = [('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)]

# Display the original list of tuples to the console
print("Original list of tuples:")
print(subject_marks)

# Sort the 'subject_marks' list of tuples based on the second element of each tuple (the marks),
# using a lambda function as the sorting key to extract the second element
subject_marks.sort(key=lambda x: x[1])

# Display the sorted list of tuples to the console
print("\nSorting the List of Tuples:")
print(subject_marks) 

Sample Output:

Original list of tuples:
[('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)]

Sorting the List of Tuples:
[('Social sciences', 82), ('English', 88), ('Science', 90), ('Maths', 97)]

Explanation:

In the exercise above -

  • subject_marks = [('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)]: Initializes a list of tuples named 'subject_marks'. Each tuple contains a subject (string) as its first element and the corresponding marks (integer) as its second element.
  • print("Original list of tuples:"): Prints a message indicating that the following output will display the original list of tuples.
  • print(subject_marks): Displays the original list of tuples ('subject_marks') to the console.
  • subject_marks.sort(key=lambda x: x[1]): Sorts the list of tuples (subject_marks) based on the second element of each tuple (i.e., the marks). It uses a lambda function as the sorting key, which extracts the second element (x[1]) for sorting purposes.
  • print("\nSorting the List of Tuples:"): Prints a message indicating that the following output will display the sorted list of tuples.
  • print(subject_marks): Displays the sorted list of tuples (now sorted based on marks) to the console.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to create a function that takes one argument, and that argument will be multiplied with an unknown given number.
Next: Write a Python program to sort a list of dictionaries using Lambda.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/lambda/python-lambda-exercise-3.php