Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda and functions in Python

Tags:

python

I have beginner two questions

  1. What does *z or *foo or **foo mean regarding function in Python.
  2. This works - a = lambda *z :z But this does not - a = lambda **z: z. Because it is supposed to take 0 arguments. What does this actually mean?
like image 539
Sumod Avatar asked Mar 08 '11 12:03

Sumod


People also ask

What is the function of lambda function?

Lambda functions are intended as a shorthand for defining functions that can come in handy to write concise code without wasting multiple lines defining a function. They are also known as anonymous functions, since they do not have a name unless assigned one.

Is lambda expression a function in Python?

Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression).

What are Python functions?

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function.


2 Answers

*z and **z in Python refer to args and kwargs. args are positional arguments and kwargs are keyword arguments. lambda **z doesn't work in your example because z isn't a keyword argument: it's merely positional. Compare these different results:

    >>> a = lambda z: z
    >>> b = lambda *z: z
    >>> c = lambda **z: z
    >>> a([1,2,3])
    [1, 2, 3]
    >>> b([1,2,3])
    ([1, 2, 3],)
    >>> c([1,2,3]) # list arg passed, **kwargs expected
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: <lambda>() takes exactly 0 arguments (1 given)
    >>> c(z=[1,2,3]) # explicit kwarg
    {'z': [1, 2, 3]}
    >>> c(x=[1,2,3]) # explicit kwarg
    {'x': [1, 2, 3]}
    >>> c({'x':[1,2,3]}) # dict called as a single arg
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: <lambda>() takes exactly 0 arguments (1 given)
    >>> c(**{'x':[1,2,3]}) # dict called as **kwargs
    {'x': [1, 2, 3]}
    >>> b(*[1,2,3]) # list called as *args
    (1, 2, 3)
like image 165
kojiro Avatar answered Sep 19 '22 05:09

kojiro


Check out the link its a good blog post on How to use *args and **kwargs in Python http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

like image 45
Anuj Avatar answered Sep 22 '22 05:09

Anuj