what's wrong with "lambda x : print x/60,x%60"

Gary Herron gherron at islandtraining.com
Mon Dec 5 02:11:22 EST 2005


Mohammad Jeffry wrote:

> Dear All,
>
> Can't a lambda uses the input parameter more then once in the lambda 
> body?
> eg:
> lambda x : print x/60,x%60
>
> I tried with def and it works but got syntax error with lambda. Below 
> is an interactive sample:

Lambda evaluates a single *expression* and returns the result.  As print 
is a statement it does not qualify (and would provide nothing to return 
even if it did).  So just use a def.  It is constantly pointed out on 
this list that the lambda provides no extra expressive power, it is 
merely a shortcut and, as you just found out, a rather restrictive one 
at that.

See the reference manual entry: 
http://www.python.org/doc/2.4.2/ref/lambdas.html

As for your next question,
        lambda x : x/60,x%60
is parsed as
        (lambda x: x/60), x%60
That is, the scope of the lambda (and its x) are finished by the comma.
Perhaps being more explicit about the returned tuple would produce what 
you want.
        lambda x : (x/60,x%60)

Gary Herron

>
> linuxlah at algorhythm ~ $ python
> Python 2.4.2 (#1, Nov 18 2005, 19:32:15)
> [GCC 3.3.6 (Gentoo 3.3.6, ssp-3.3.6-1.0, pie-8.7.8)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> def func_hrs(x): print x/60,x%60
> ...
> >>> func_hrs(400)
> 6 40
> >>> lambda_hrs = lambda x : print x/60,x%60
>   File "<stdin>", line 1
>     lambda_hrs = lambda x : print x/60,x%60
>                                 ^
> SyntaxError: invalid syntax
> >>>
>
> My main concern is how can I do this in lambda?
>
>
>
> -- 
> And whoever does an atom's weight of evil will see it. 





More information about the Python-list mailing list