python defaultdict: 0 vs. int and [] vs list python defaultdict: 0 vs. int and [] vs list python python

python defaultdict: 0 vs. int and [] vs list


All that defaultdict requires is a callable object that will return what should be used as a default value when called with no parameters.

If you were to call the int constructor, it would return 0 and if you were to call lambda: 0, it would return 0. Same with the lists. The only difference here is that the constructor will always use it's logic to create the object. A lambda, you could add additional logic if you chose to do so.

e.g.,

# alternating between `0` and `[]`from itertools import countfactory = lambda c=count(): 0 if next(c) % 2 else []superdict = defaultdict(factory)