CompactSpaces
CompactSpaces

Reputation: 3

A request for explaining a piece of basic python code about dictionaries

I want to ask you for help. I have started learning Python, but I am at the very beginning. From the website I took the following code:

def take_second(elem):
  return elem[1]

random = [(2, 2), (3, 4), (4, 1), (1, 3)]

take_second(random) # (3, 4)

sorted(random, key = take_second) # [(4, 1), (2, 2), (1, 3), (3, 4)]

The problem is, that I have no idea how it works, how it is sorted according to the function take_second(). I understand how the function take_second() works - it always takes the element on the 1st position (index = 1). So, for the variable random which is a list, it is a tuple (3, 4). And here the problem starts. How the variable random is sorted next?

I'm sorry probably it is extremely easy, but I have been thinking for a while about it and nothing, seriously.

Is here anyone who can help me? I would be grateful.

Upvotes: 0

Views: 45

Answers (1)

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

Lets say you had a regular non nested list

listy = [2,4,3,1]

then when you run sorted on it, it will sort it by comparing each element

listy = [1,2,3,4]

but when you have a list like

random = [(2, 2), (3, 4), (4, 1), (1, 3)]

you may want to specify how it should be sorted. By taking the function take_second as a key in sorted, it allows the computer to know what to sort the list by. In this case, the computer will compare the second value in each element to determine the ordering, and as you can see in the output, the second values from each tuple do go 1,2,3,4.

sorted(random, key = take_second) # [(4, 1), (2, 2), (1, 3), (3, 4)]

Upvotes: 1

Related Questions