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']
Best answer
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!