Create lambda expressions on the fly

def multipliers():
  l = []
  for i in range(4):
    l.append(lambda x : x * i )
  return l

>>> ll[0](2)
6
>>> ll[1](2)
6
>>> ll[2](2)
6
>>> ll[3](2)
6

Can you explain the result here? I was hoping to get:

0
2
4
6
+4
source share
3 answers

The problem is that, as people say, is inot a local variable lambda. You should fix this: using the default parameter value, changing during the loop:

>>> def multipliers():
  l = []
  for i in range(4):
    l.append(lambda x, i=i : x * i )
  return l

>>> lst = multipliers()
>>> lst[0](2)
0
>>> lst[1](2)
2
>>> lst[2](2)
4
>>> lst[3](2)
6
>>> 
+2
source

, Pythons . , , , . , - , multipliers(), i . , , , for , i 3. , , 3, , 2, 6

: http://www.toptal.com/python/interview-questions

+4

i lambda. , : Python i, , .

+1

All Articles