2

Can someone please explain how this code works. How the isisnstance function in the lambda function sorts the list

def db_sort(arr):
    return sorted(arr, key=lambda x: (isinstance(x,str) ,x))
db_sort(['a', 'w', 'u', 'y', 6, 2, 3, 4, 5])

output:

[2, 3, 4, 5, 6, 'a', 'u', 'w', 'y']

1 Answer 1

3

The lambda function creates tuples of a Boolean value and the original value itself. So sorted is applied on the following input:

(True, 'a') (True, 'w') (True, 'u') (True, 'y') (False, 6) (False, 2) (False, 3) (False, 4) (False, 5)

It puts the entries with a False entry first, and then the True elements (the strings in this example). Then it sorts the False elements in logical order after the second tuple entry and the True elements in logical order as well. Think of it as a kind of hierarchical sorting.

So you end up with

(False, 6) (False, 2) (False, 3) (False, 4) (False, 5) (True, 'a') (True, 'w') (True, 'u') (True, 'y')

after the first level of sorting and with

(False, 2) (False, 3) (False, 4) (False, 5) (False, 6) (True, 'a') (True, 'u') (True, 'w') (True, 'y')

after the second level. This way you end up with the final order of your array (I suppose you missed 6 accidentally).

[2, 3, 4, 5, 6, 'a', 'u', 'w', 'y']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.