In [19]: %cpaste Pasting code; enter '--' alone on the line to stop or use Ctrl-D. :A = [12, 73, 2876, 2755, 28, 9, 127, 847, 25, 551, 37, 898, 14, 29] : :cur_buf = 0 :for i in [0, 1, 2, 3, 4]: : for j in xrange(len(A)): : if A[j] % 5 == i: : A[j], A[cur_buf] = A[cur_buf], A[j] : cur_buf += 1 : :print A :print map(lambda x: x % 5, A) :-- [2755, 25, 2876, 551, 127, 847, 12, 37, 73, 28, 898, 9, 14, 29] [0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4]