-1

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)
JR Unisa
  • 19
  • 3
  • It needs the `e` argument because otherwise `sort()` wouldn't be able to pass each list item to it – Mathias R. Jessen Jan 31 '23 at 16:06
  • Here, e is just the name for an argument. It could be literally anything. You can keep it x, y or even PYTHON that doesn't matter. This is required since you are returning the length of the argument by using the len() function. Without passing in the argument, you cannot identify the length of None. – The Myth Jan 31 '23 at 16:07
  • 1
    `sort()` passes in the argument to the key function. In this specific case you don't even need `myFunc` since `len` accepts a single argument and can thus be used as a key function directly: `cars.sort(key=len)` – kindall Jan 31 '23 at 16:09
  • Sorry, I wasn't clear about my confusion. In the cars.sort(key=myFunc) line, how is it that when you call the myFunc function you don't need to include the argument? – JR Unisa Jan 31 '23 at 16:14
  • @JRUnisa Everything in Python is an object, even functions and classes themselves, so you can pass functions as arguments or even assign them to variables, etc. See: [Python function as a function argument?](https://stackoverflow.com/questions/6289646/python-function-as-a-function-argument) – Abdul Aziz Barkat Jan 31 '23 at 16:24
  • 1
    You *aren't* calling `myFunc`; you are just passing a reference to the function to `sort` so that `sort` can call it later. – chepner Jan 31 '23 at 16:27

1 Answers1

1

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.

eswar
  • 44
  • 3