Python’s sort() has the optional argument key. You can use a lambda function as the key like so:
numbers = [1, 9, 35, 12, 13, 21, 10]
numbers.sort(key=lambda i: i % 5)
print(numbers)
A quick explanation of what’s going on here:
A lambda function is a function that is defined in-line and isn’t named.
lambda i: i % 5
is the same as:
def modulo_5(i):
return i % 5
The key argument tells the sort() method to use something other than the list items to determine sort order. The function we defined as the sort key takes the list item as its argument (we called the argument i). It then takes the list item and applies the modulo operator, which returns the remainder of dividing the item by the number we specified (5 in this case). It then does the sorting based on this remainder value. When multiple list items have the same sort key value, they are kept in the same order as they were in the original list. That is why 35 comes before 10 in the sorted list, because 35 was before 10 in the original list.
solved Sort a list of integers basis the remainder they leave when divided by 5 in an ascending order? [closed]