0

I know that an empty list as a default parameter value of a function does not behave as expected. I was wondering if it were safe to capture a list in a lambda expression:

my_lists = [[1,2], [3, 4], [5, 6]]

def foo():
    my_lambdas = []
    for i in range(3):
        my_lambdas.append(lambda my_list=my_lists[i]: my_list)
    return my_lambdas

all_lambdas = foo()

This code seems to work, each lambda in all_lambdas returning its own list.

My question is: Does capturing lists in lambdas raise similar issues as when we use lists as default parameter values? Are there any issues I should be aware of in the code above (even though it seems to work)? If there are any issues, how would I solve them?

Gradient
  • 2,253
  • 6
  • 25
  • 36
  • 1
    You've still got the exact same mutable default issue. – user2357112 Aug 04 '21 at 17:31
  • 1
    *Any* mutable object as a default argument value has the same problem; it's not unique to the empty list. – chepner Aug 04 '21 at 17:38
  • Even then, the problem is if you think you can *modify* the list being returned without affecting other return values. – chepner Aug 04 '21 at 17:39
  • I'd suggest giving https://nedbatchelder.com/text/names.html a thorough read so you understand what the actual problem with mutable default arguments is. – chepner Aug 04 '21 at 17:40
  • ```some_list``` is not defined... do you mean smt like ```lambda my_list=my_lists[i]: my_list``` ? – cards Aug 04 '21 at 17:56
  • Relevant section of the Python FAQ: [Why do lambdas defined in a loop with different values all return the same result?](https://docs.python.org/2/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result) – 0x5453 Aug 04 '21 at 17:58

0 Answers0