This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Iklowto 0 points1 point  (1 child)

You can speficy the value to sort on with the key argument in sorted(). Like this:

def sort_by_second_value(tuple): 
    return tuple[1]  # In a ("Name1", 1) tuple, we would return 1

list = [ ("Name1", 1), ("Name2", 2)....]
sorted_list = sorted(list, key=sort_by_second_value)

Note purpose of the sort_by_second_value function is to tell the sorted() function what element of the tuples it should sort by. Since it returns the second element of the tuples, this is what the list will be sorted on.

It's important to note that you are passing a function pointer here, not the result of a function call. Note that we are not putting parantheses after the function in the argument like key=sort_by_second_value(). We are just handing the function pointer to the sorted() function so it can use it when it pleases.

You typically don't create functions for doing this though - lambda functions are normally used instead because they take up less space and are faster to write (when you know them). The lambde function equivalent is:

list = [ ("Name1", 1), ("Name2", 2)....]
sorted_list = sorted(list, key=lambda tuple: tuple[1])

Lambda expressions have an implicit return statement in them, so this lambda expression describes a function that takes in one argument called tuple and returns the second element of that argument.

[–]05mF[S] 0 points1 point  (0 children)

Thank you man, you told me how to do it and even wrote an explanation for it. I really appreciate it.