Search code examples
pythonlambdacollectionsdefaultdict

Python defaultdict


I found something strange that I couldn't understand. This is the case:

from collections import defaultdict
a = defaultdict(lambda: len(a))

This is just the part of the code, and the code has never defined 'a' above.

The questions are:

  • Is it possible to use defaultdict as is, not specifying the variable previously?
  • If possible, what is the meaning of that code?

Solution

  • Maybe it is best explained in an example:

    >>> a = defaultdict(lambda: len(b))
    >>> b = 'abcd'
    >>> a[0]
    4
    

    As you can see, it is possible to use b in the lambda even though the b does not yet exist at that point. What is important is that b exists at the time when the lambda is executed. At that point, Python will look for a variable named b and use it.


    Note also that the original code does not necessarily use length of the defaultdict itself. It simply evaluates whatever a is at that point. See this example:

    >>> a = defaultdict(lambda: len(a))
    >>> a['a']
    0
    >>> a['b']
    1
    

    So far, so good. But then rename some things:

    >>> x = a
    >>> a = []
    >>> x['c']
    0
    >>> x['d']
    0
    

    Now the deaultdict is named x, but it does not use len(x). It still uses len(a). This caveat may become important if you sent the defaultdict to a function where a does not mean anything.