Q:

Lambda and multiple statements in Python

Can anyone explaine that behavior of lambda functions?
import sys
X = lambda: sys.stdout.write('first');sys.stdout.write("second")
X()

Returns:
-> secondfirst
And one more problem:
lambda: sys.stdout.write("...");sys.exit(0) 

Or 
lambda: sys.exit(0);sys.stdout.write("...")

Doesn't execute correctly.
And one more question, why in first primer execution flow goes from right to left?
Trying with:
Python3+(3.4, 3.2) 
OS: Linux (Ubuntu), OSX

A:

sys.stdout.write("second") is not part of the lambda.
'second' is always printed even if you don't call X.
In other words calling X only prints 'first'.
Your code can be rewritten as;
import sys
X = lambda: sys.stdout.write('first')
sys.stdout.write("second")
print X()

If you want two statements executed by the lambda place them in a tuple;
lambda: (sys.stdout.write('first'),sys.stdout.write("second"))

A:

There are two statements on on line,  first is in a lambda that only gets called after the sys.stdout.write("second") has already run. X() calls the lambda. 
So it does not go right to left, we just have a lambda that only gets called on the next line.  It is no different to defining a function, writing to sys.stdout and then calling that function.
Doing the equivalent with a normal function:
sys.stdout.write("second") 
def x():
    sys.stdout.write('first')

x()    

For your other example you need to assign the lambda and then call it:
x= lambda: sys.exit(0);sys.stdout.write("...")
x()

Using a ; and having multiple statements on one line is not pythonic or a very good idea generally.

A:

The syntax for lambda is:
lambda <args>: <expression>

where <expression> must be a single expression. It cannot be a statement, or multiple statements, or multiple expressions separated by ;.
What happens in your code is that lambda has higher priority over ;, so that gets parsed as: X = lambda: sys.stdout.write('first') followed by sys.stdout.write("second"). Adding parentheses around sys.stdout.write('first') ; sys.stdout.write("second") would not work and produce a syntax error.
My trick to do multiple things inside a lambda is:
f = lambda: [None, sys.stdout.write('first'), sys.stdout.write("second")][0]

and the other one:
f = lambda: [None, sys.stdout.write("..."), sys.exit(0)][0]

However that kind of defeats the purpose of a lambda function, which is to do something short and really simple.
I guess that would still be OK in your specific example, but kind of looks like a hack.

