In Python 2, I can write:
In [5]: points = [ (1,2), (2,3)]
In [6]: min(points, key=lambda (x, y): (x*x + y*y))
Out[6]: (1, 2)
But that is not supported in 3.x:
File "<stdin>", line 1
min(points, key=lambda (x, y): (x*x + y*y))
^
SyntaxError: invalid syntax
The straightforward workaround is to index explicitly into the tuple that was passed:
>>> min(points, key=lambda p: p[0]*p[0] + p[1]*p[1])
(1, 2)
This is very ugly. If the lambda were a function, I could do
def some_name_to_think_of(p):
x, y = p
return x*x + y*y
But because the lambda
only supports a single expression, it's not possible to put the x, y = p
part into it.
How else can I work around this limitation?
min(points, key=lambda p: sum(x*x for x in p)
– Enactmentlambda
to get removed from the language entirely then to reverse changes that made it harder to use, but you could try posting on python-ideas if you'd like to express a desire to see the feature added back. – EclatIt's probably more likely for lambda to get removed from the language
why would lambda be removed?changes that made it harder to use
? you think tuple unpacking makes lambda harder to use ? – Athelinglambda
in the same spirit as he opposesmap
,reduce
andfilter
. – Huskinglambda
was slated for removal in py3k as it's basically a blight on the language. But nobody could agree on a proper alternative for defining anonymous functions, so eventually Guido threw up his arms in defeat and that was that. – Pepitamap
andfilter
are best replaced by comprehensions, I do likereduce
) – Athelingstar(f)
) seems a pretty nice workaround. forklifted. – Dorindastar
function is removed. check here for revision – Cockaigne