Lambda vs defined functions

Diff between lambda and regular functions

  1. Defined functions do not return anything if not explicitly returned whereas the lambda function does return an object by default
  2. The def functions must be declared in the namespace. Whereas lambda without any declaration

Indirect function call

https://github.com/matacoder/senior#best-practice-decorators-for-functions

Defined function

Immutable, mutable objects
Immutable, mutable objects
image
image

Lambda

image
image

Questions

def a():
    return [lambda x: y * x for y in range(5)]

for i in a():
    print(i(2))

# Q: What will be printed in screen?
# 8
# 8
# 8
# 8
# 8

# Q: Why, and how to solve that?
return [lambda x, y=y: y * x for y in range(5)]

def outer(n):
    def inner(x):
        return x*n
    return inner

a = outer(5)
a(5)
# Output: 25

What will be printed out by the last statement below?

>>> flist = []
>>> for iin range(3):
...    flist.append(lambda: i)
...
>>> [f() for fin flist] # what will this print out?

In any closure in Python, variables are bound by name. Thus, the above line of code will print out the following:

[2, 2, 2]

Presumably not what the author of the above code intended!

workaround is to either create a separate function or to pass the args by name; e.g.:

>>> flist = []
>>> for iin range(3):
...    flist.append(lambda i = i : i)
...
>>> [f()for fin flist]
[0, 1, 2]
SuperMade with Super