lambda requirements

piet at cs.uu.nl piet at cs.uu.nl
Mon Jul 3 10:50:38 EDT 2000


>>>>> "Wolfgang Thaemelt" <wolfgang.thaemelt at orsoft.de> (WT) writes:

WT> Running the script:
WT> #----------------------------------------- begin of script
WT> def SymmetricDifference(list1, list2):
WT> #      global _list1
WT> #      global _list2

WT>       _list1 = list1
WT>       _list2 = list2

WT>       _onlylist1 = filter(lambda x: x not in _list2, _list1)

WT>       return _onlylist1

WT> if __name__ == '__main__':
WT>   a = [1,2,3,4,5]
WT>   b = [3,4,5,6,7]
WT>   x = SymmetricDifference(a,b)

WT>   print x
WT> #---------------------------------------- end of script

WT> gives the error:

WT> Traceback (innermost last):
WT>   File "E:\up\000701\symmdiff.py", line 16, in ?
WT>     x = SymmetricDifference(a,b)
WT>   File "E:\up\000701\symmdiff.py", line 9, in SymmetricDifference
WT>     _onlylist1 = filter(lambda x: x not in _list2, _list1)
WT>   File "E:\up\000701\symmdiff.py", line 9, in <lambda>
WT>     _onlylist1 = filter(lambda x: x not in _list2, _list1)
WT> NameError: _list2

WT> If the comment characters "#"  are removed from the "global" statements
WT> everything works fine.

WT> Is there some requirement on a lambda violated in the script?

Python has only two scopes: the local variables of the function (which is
the lambda in this case) and the global ones of the module. (O.K. the
builtins also).
There are no intermediate scopes visible, in your case that would be the
local variables of SymmetricDifference.
The usual trick is to copy these things as additional parameters of the
lambda, where you can even use the same name.
In your case only list2 has to be copied, there is no need to copy list1.
Also the variable for the result is not needed, so this is a compacr
definition that works:

def SymmetricDifference(list1, list2):
      return filter(lambda x,_list2=list2: x not in _list2, list1)

Using list2 rather than _list2 would also work.
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.van.Oostrum at hccnet.nl



More information about the Python-list mailing list