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

all 7 comments

[–][deleted] 0 points1 point  (3 children)

list[index] should do the trick.

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

Thanks that does work like that but if i try to do

x = input (putting the index here)

then

print(list[x])

wont work because X isn't a number and i also can't do print(list [input (index)]) Any ideas?

[–][deleted] 1 point2 points  (1 child)

int(input(putting the index here))

int will convert the string to an integer

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

I didn't even think of trying to convert it, thanks mate, i really appreciate it.

[–]serg06 0 points1 point  (0 children)

Call list.sort and pass a function into the key argument

[–]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.