Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python key = lambda substitutes

Is there any way to write this code without using lambda, preferably using basic python code?

sorted(list1, key=lambda x: x[1])

I’m using it to sort the second element of a list of tuples, from lowest to highest. I’ve tried some things but none of them work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Sure, you can achieve the same result without using a lambda function by defining a regular function. Here’s how you can do it:

  1. Define a function that takes a tuple as an argument and returns the second element of the tuple.
  2. Use this function as the key in the sorted function.

Here’s the Python code:

def second_element(tuple):
    return tuple[1]

sorted_list = sorted(list1, key=second_element)

In this code, the second_element function is used to extract the second element of each tuple. The sorted function then sorts the tuples based on these second elements.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading