I want to sort a list based on how close a number in the list is to a given number. so for example:
target_list = [1,2,8,20] number = 4 then probably sorted l
You can use the key parameter of the sorted function
key
sorted
>>> target_list = [1,2,8,20] >>> sorted(target_list, key=lambda x: abs(4-x)) [2, 1, 8, 20]
Or if you want to sort it in place, even the list sort method accepts a key.
sort
>>> target_list.sort(key=lambda x: abs(4-x)) >>> target_list [2, 1, 8, 20]