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.
>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:
- Define a function that takes a tuple as an argument and returns the second element of the tuple.
- 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.