1

I a little bit confused about this one liner

tree = lambda: defaultdict(tree)

How it is possible? (lambda should return default dict but how we can put first arg as tree?)

1
  • 3
    functions are evaluated when they're called, so you can put anything on the right hand side that you want. tree = lambda: bananarama is valid, up until you call it and the lookup on bananarama fails. Commented May 4, 2014 at 13:45

1 Answer 1

1

Lambdas delay evaluation of their contents until they are called, so when tree() is called and defaultdict(tree) is evaluated, tree will be well defined, and thus not cause any issues. A more explicit example:

>>> foo = lambda: bar
>>> foo()
NameError: global name 'bar' is not defined
>>> bar = 5
>>> foo()
5

As for what this particular lambda does: The first argument to defaultdict is a factory method used when a key is missing(see documentation for details). So the one-liner

tree = lambda: defaultdict(tree)

defines a dictionary that by default contains other dictionaries. I.e. a tree.

For example:

my_tree = tree()

creates a new tree, and the following two lines do the same thing:

my_tree["foo"]
my_tree["foo"] = defaultdict(tree)

Namely creating a new subtree named "foo". New elements can thus be added deep into the tree without creating each subtree manually. For example:

root = tree()
root["foo"]["bar"]["baz"] = False
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.