Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python sort method key parameter

In the myFunc function below, where is the (e) argument passed in from? (I hope I’m using the right terminology)

# A function that returns the length of the value:
def myFunc(e):
  return len(e)

cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']

cars.sort(key=myFunc)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

the function myFunc is called by cars.sort(key=myFunc) and each item in the list passed as an argument to myFunc. parameter name is not required here as it can work with the positional parameter. but we still need to have one parameter myFunc so that it can receive the passed value.

also the code can be simplified like below by using len() method directly instead of wrapping it in myFunc.

cars.sort(key=len)

Hope this helps.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading