Ankur Agarwal
Ankur Agarwal

Reputation: 24758

How is this sorting code working?

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']

Upvotes: 6

Views: 119

Answers (2)

alecxe
alecxe

Reputation: 473833

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"].

Upvotes: 1

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

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!

Upvotes: 7

Related Questions