How is this sorting code working? I cannot understand how the values returned by the iterator are being used to sort the list?
mylist=["zero","two","one"]
list1=[3,1,2]
it = iter(list1)
sorted(mylist, key=lambda x: next(it))
Output:
['two', 'one', 'zero']
It works like this - the key=lambda x: next(it)
part is stating: assign an order value of 3
, then 1
then 2
to each of the elements in mylist
. So two
comes first, then one
then zero
:
["zero", "two", "one"] # original list
[ 3, 1, 2 ] # assign this order to each element
Now, after sorting:
[ 1, 2, 3 ] # sorted keys
["two", "one", "zero"] # and there you go!
next(it)
returns next item of the iterable every time it's called:
>>> list1=[3,1,2]
>>> it = iter(list1)
>>> print next(it)
3
>>> print next(it)
1
>>> print next(it)
2
key
is a function that is called on each list element for making comparisons.
sorted()
: If you don't specify key
parameter it will compare item values, if you provide key
- it uses the result of key
function calls for making comparisons between items of the list.
So, for "zero"
it is 3
, for "two"
- 1
, for "one"
- 2
. Since 1 < 2 < 3
, the result is ["two", "one", "zero"]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With