First of all, you have a instead of s in recursive permut call.
return [ e + [l[0]] for e in permut(a, l[1:])] + [l+[s]]
First, it calculates permut(s, l[1:]), that is: tries to permute s and the part of the list without the first element. It throws the first element away as long there's any, then the recursive call returns [[s]].
Now, going backwards in calls, s is "added" to the every element of recursively created list, then given l is appended, and the results are:
# l == []
return [['a']]
# e == ['a']
# l == [3], l[0] == 3
return [['a'] + [3]] + [[3] + [a]]
# equals [['a', 3], [3, 'a']]
# e == ['a', 3] then [3, 'a']
# l == [2, 3], l[0] == 2
return [['a', 3] + [2], [3, 'a'] + [2]] + \
[[2, 3] + [a]]
# equals [['a', 3, 2], [3, 'a', 2], [2, 3, 'a']]
# e == ['a', 3, 2] then [3, 'a', 2] then [2, 3, 'a']
# l == [1, 2, 3], l[0] == 1
return [['a', 3, 2] + [1], [3, 'a', 2] + [1], [2, 3, 'a'] + [1]] + \
[[1, 2, 3] + ['a']]
# equals [['a', 3, 2, 1], [3, 'a', 2, 1], [2, 3, 'a', 1], [1, 2, 3, 'a']]
Maybe it's not beautiful to read, but it kind of works. You can see that e is extracted as single element of the list returned on the previous level.
You could also try:
def tee(parm):
print parm
return parm
And redefine permut as:
def permut(s,l):
if l == []: return [[s]]
return [ e + [l[0]] for e in tee(permut(s, l[1:]))] + [l+[s]]
My output:
[['a']]
[['a', 3], [3, 'a']]
[['a', 3, 2], [3, 'a', 2], [2, 3, 'a']]
[['a', 3, 2, 1], [3, 'a', 2, 1], [2, 3, 'a', 1], [1, 2, 3, 'a']]
Which covers recursive calls.