Reputation: 2331
This code is used to sort a big_list but put the small_list in the beginning of the big_list. I don't understand how the argument 'x' is passed to the def helper and what's the meaning of return (0,x) and (1,x) here. Any help would be greatly appreciated.
def sort_list(value, group):
def helper(x):
if x in group:
return (0,x)
return (1,x)
value.sort(key=helper)
big_list = [8,3,1,2,5,4,7,6]
small_list = [2,3,5,7]
sort_list(big_list, small_list)
print(big_list)
[2, 3, 5, 7, 1, 4, 6, 8]
Upvotes: 0
Views: 74
Reputation: 198418
(0,x)
is a two-member tuple. The key insight is that tuples sort by first element, disambiguating by second element, then next.... and only being equal when each member is equal. Thus, for example,
(0, 0) < (0, 1) < (0, 2) < (1, 0) < (1, 1) < (1, 2)
Thus, helper
as the sort key will sort any elements in group
before any elements outside group
; but then sort by value inside each part. This accounts for 2, 3, 5, 7
being ordered, 1, 4, 6, 8
being ordered, and the former coming before the latter.
Upvotes: 1