0
def bigSorting(unsorted):
   return sorted(unsorted, key=lambda s: (len(s), s))

I am trying to understand this solution I saw on "HackerRank". The example of unsorted list given is:

unsorted = ['1','200','150','2'] 

How does key=lambda s: (len(s), s)) work?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Alex
  • 1
  • 1
    It's sorting first by length, and then lexicographically among all the strings with the same length. This makes it equivalent to sorting numerically. – Barmar Jun 02 '21 at 19:28
  • 4
    Are you asking how/what a `lambda` is, what passing arguments by name (e.g. `key=`) means, or what `sorted` is doing with that argument? Virtually all of those are either already answered here or described in the docs for `sorted`, but you need to be clear on what is confusing you. – ShadowRanger Jun 02 '21 at 19:28
  • @Barmar: So for this case, `key=int` would also do the trick, at least for the inputs provided. – ShadowRanger Jun 02 '21 at 19:29
  • Yes, it would. It's HackerRank, they're trying to show "clever" solutions. – Barmar Jun 02 '21 at 19:33
  • Thank you @Barmar, key = int doesn't work for all test cases. – Alex Jun 02 '21 at 19:44
  • Maybe they're not all integers like in the example you posted. – Barmar Jun 02 '21 at 19:45

0 Answers0