0

em...I feel confused about this code, I am really new to coding, and wonder anyone can help:

def takeSecond(elem):# If I pass the argument as a list, why don't I need to specify it here? 
     return elem[1]  # what return elem[1] means,does it return the y in (x,y)? but why!?
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
random.sort(key=takeSecond) # key = takeSecond what is this even mean lol?..
print('Sorted list:', random)
2

2 Answers 2

1

Let's say you have a list of items, which contains:

list = [a,b,c]

If you use the following piece of code:

def func():
    return list[1]

You'd get "b" as output. The number "1" is not the first element, it's the second element. The counting in python starts at 0. So basically, if you want to access "a", you have to use:

def func():
    return list[0]

Because 0 = a, 1 = b, 2 = c, and so on. If you change return elem[1] to return elem[0] you get the variable x.

Sign up to request clarification or add additional context in comments.

Comments

1
  • Here your trying to sort based on second value in given list
  • takeSecond function is always returns the second value in the given element.
  • In random.sort() method calling with your passing key parameter as takeSecond function, which means sorting perform based on that element it happen. In our case it will return second element. So sorting is perform based on second element
  • And then printing the sorted list

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.