Python sorting with square as key

Viewed 213

Saw some code on a book and just cannot follow it, even try to decipher by run step-by-step and it's still Greek to me... (on 2nd Mon. journey) (I kind of know each part, eg. range or sorted or lambda- except putting together)

sorted(range(-3,4), key=lambda x: x*x)

Output:

[0,-1,1,-2,2,-3,3]
3 Answers
sorted(range(-3,4), key=lambda x: x*x)

Try to do it step by step. Let's start with range, range here will provide numbers -3, -2, -1, 0, 1, 2, and 3.

sorted then runs on each of these items and uses the function provided in the key parameter. Each of these items is passed on the x parameter of the lambda. The lambda then handles this x (represented as the number in the range) and performs some operations, in your case, it just gets the square of the number x. The square value then gets returned and the sorted function uses this returned square value in comparing in ascending order (remember that sorted arranges the list in ascending order unless specified as reverse=True).

The purpose of the key function is to only tell how to compare each item in the iterable/list passed. But it does not affect the final list of elements that will be returned. It will still use the passed list. So these values -3, -2, -1, 0, 1, 2, and 3 will be the elements of the returned list by the sorted function, only arranged in accordance with the key parameter.

Hope it helps and makes sense.

range is defined as range(start, stop, step) and the stop parameter is not included.

sorted defined as sorted(iterable, key=key, reverse=reverse) seems to work like this:

The original input values are outputted but sorted by a key, in this case by their square. The square converts the negative values into positive ones, then sorting is applied and finally, the original values are returned in order.

Tested this on the command line:

print(sorted(range(-3,4)))
# [-3, -2, -1, 0, 1, 2, 3]

print(sorted(range(-3,4), key=lambda x: x*x))
# [0, -1, 1, -2, 2, -3, 3]

The Python Docs about sorting; it says for both sorted() (and also sort()) the sort is stable:

Sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved.

It works like this:b

The range function returns the value [-3, -2, -1, 1, 2, 3].

Now the confusing piece, the key argument, calls lambda for each of the values to be sorted and instead use those value to sort them.

That means the list was sorted by their square `[9, 4, 1, 0, 1, 4, 9] and not by their actual number as returned by the range function.

For example:

sorted(range(-3,4), key=lambda x: x*-1)

would return [3, 2, 1, 0, -1, -2, -3]

Related