Python sort method key parameter
Question:
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)
Answers:
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.
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)
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.