Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python lambda does not accept tuple argument [duplicate]

I am running Eclipse SDK v3.6 with PyDev v2.6 plugin on two PC, with Linux and Windows.

I would like to pass a tuple as an argument, like:

foo = lambda (x,y): (y,x)
print (foo((1,2)))

This works on Linux and gives the correct result:

> (2,1)

On Windows it rises an error:

foo = lambda (x,y): (y,x)
             ^
SyntaxError: invalid syntax

How to solve the problem?

like image 902
Dmitry Avatar asked Jul 04 '12 11:07

Dmitry


People also ask

Can lambda function accept multiple arguments?

Just like a normal function, a Lambda function can have multiple arguments with one expression. In Python, lambda expressions (or lambda forms) are utilized to construct anonymous functions. To do so, you will use the lambda keyword (just as you use def to define normal functions).

Can Lambda return 2 values Python?

That's not more than one return, it's not even a single return with multiple values. It's one return with one value (which happens to be a tuple).

Can lambda function evaluate multiple expressions?

Python lambda functions accept only one and only one expression. If your function has multiple expressions/statements, you are better off defining a function the traditional way instead of using lambdas.

Can Python lambda have multiple statements?

Lambda functions does not allow multiple statements, however, we can create two lambda functions and then call the other lambda function as a parameter to the first function.


1 Answers

You are probably running Python 3.x on Windows, and Python 2.x on Linux. The ability to unpack tuple parameters was removed in Python 3: See PEP 3113.

You can manually unpack the tuple instead, which would work on both Python 2.x and 3.x:

foo = lambda xy: (xy[1],xy[0])

Or:

def foo(xy):
    x,y = xy
    return (y,x)
like image 149
interjay Avatar answered Oct 19 '22 17:10

interjay