I have beginner two questions
*z or *foo or **foo mean regarding function in Python.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?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.
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).
A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function.
*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)
                        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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With