swap = lambda a,x,y:(lambda f=a.__setitem__:(f(x,(a[x],a[y])), f(y,a[x][0]),f(x,a[x][1])))()
Have a look () at the end? The inner lambda is not coming back, her name is.
The function performs the equivalent
def swap(a, x, y): a[x] = (a[x], a[y]) a[y] = a[x][0] a[x] = a[x][1]
But suppose we want to do this in lambda. We cannot use appointments in lambda. However, we can call __setitem__
for the same effect.
def swap(a, x, y): a.__setitem__(x, (a[x], a[y])) a.__setitem__(y, a[x][0]) a.__setitem__(x, a[x][1])
But for lambda we can have only one expression. But since these are function calls, we can wrap them in a tuple
def swap(a, x, y): (a.__setitem__(x, (a[x], a[y])), a.__setitem__(y, a[x][0]), a.__setitem__(x, a[x][1]))
However, all those __setitem__
pushing me, so let them go:
def swap(a, x, y): f = a.__setitem__ (f(x, (a[x], a[y])), f(y, a[x][0]), f(x, a[x][1]))
Dagnamit, I canโt get away with adding another job! I know that it is permissible to use the default parameters.
def swap(a, x, y): def inner(f = a.__setitem__): (f(x, (a[x], a[y])), f(y, a[x][0]), f(x, a[x][1])) inner()
Good move on to lambdas:
swap = lambda a, x, y: lambda f = a.__setitem__: (f(x, (a[x], a[y])), f(y, a[x][0]), f(x, a[x][1]))()
Which brings us back to the original expression (plus / minus typos)
All this leads to the question: Why?
The function should have been implemented as
def swap(a, x, y): a[x],a[y] = a[y],a[x]
The original author has gone astray to use a lambda rather than a function. Maybe for some reason he does not like a nested function. I dont know. All I will say is its bad code. (if there is no mysterious excuse for this).