about lambda

Duncan Booth duncan.booth at invalid.invalid
Sun Nov 20 16:17:18 CET 2005

Shi Mu wrote:

> what does the following code mean? It is said to be used in the
> calculation of the overlaid area size between two polygons.
> map(lambda x:b.setdefault(x,[]),a)
> Thanks!

Assuming b is a dict, it is roughly equivalent to the following (except 
that the variables beginning with _ don't exist):

_result = []
for _key in a:
   if _key not in b:
       b[_key] = []

A more usual way to write this would be:

result = [b.setdefault(key, []) for key in a]

I added an assignment because I'm assuming that even though you didn't show 
it the original expression made some use of the resulting list, otherwise 
it is just wasting time and effort obfuscating something which could be 
more simply written as:

for key in a:
   if key not in b:
       b[key] = []

More information about the Python-list mailing list