2

I encountered a strange behavior of a function in Python:

 def test_path(n, tree=[]):
            print (n, id(tree), tree)
            tree.append(n)
            if n < 3: 
                test_path(n+1, tree)

Optional argument of recursive function does not re-initialized on subsequent calls:

>>> test_path(0)
(0, 140065391163800, [])
(1, 140065391163800, [0])
(2, 140065391163800, [0, 1])
(3, 140065391163800, [0, 1, 2])

>>> test_path(1)
(1, 140065391163800, [0, 1, 2, 3])
(2, 140065391163800, [0, 1, 2, 3, 1])
(3, 140065391163800, [0, 1, 2, 3, 1, 2])

>>> test_path(1, [])
(1, 140065391262032, [])
(2, 140065391262032, [1])
(3, 140065391262032, [1, 2])

Why three object is the same on all calls when undefined? What am I doing wrong?

bvasiliev
  • 121
  • 2

0 Answers0