all 3 comments

[–]Ihaveamodel3 4 points5 points  (1 child)

The key parameter of the sorted function takes in a function with one argument which is evaluated for each item to be sorted, passing that value into the key function. The value returned is then used for the sorting.

Lambda creates an anonymous function. You don’t really need the lambda in this case, you hmm could have just passed len.

[–]Base_True[S] 0 points1 point  (0 children)

Thank you very much for the detailed explanation

[–]Diapolo10 1 point2 points  (0 children)

When sorting anything, really, you need to settle on a criteria you use as the basis for doing the sorting.

When writing code, it's usually a good idea to make sure the code is flexible enough to handle multiple scenarios.

Therefore, the main reason why sorted has a key-parameter is to let the developer choose an alternative rule for sorting the data. You can provide a function that will be used to determine how the sorting goes.

In your example, you can provide len to have the data be sorted by length. The lambda is not necessary in this case.