This return returns an understanding of the list, the elements of which are created by inserting the first element l at each position p , from the first to the last - p , in turn, is a list of lists obtained by the recursive call to perm , which excludes the first element l (and thus , rearranges all other elements in all possible ways).
If you do not understand recursion, this is not entirely trivial to explain ;-). If you do not understand the understanding of lists, they trivial to explain - that return semantically equivalent
result = [] for i in range(sz): for p in perm(l[1:]): result.append(p[:i]+[l[0]]+p[i:]) return result
it also shows how inefficient this code is: it calls perm recursively sz times, and obviously there is no need for it. It would be much better to just swap the two for loops:
result = [] for p in perm(l[1:]): for i in range(sz): result.append(p[:i]+[l[0]]+p[i:]) return result
and the equivalent of this, much better code, is understanding the list with replacing two for :
return [p[:i]+[l[0]]+p[i:] for p in perm(l[1:]) for i in range(sz)]
source share