2

I was running into some problems with a project on python 3, and decided to create that smaller version to understand what was happening. Turns out that it just confused me even more. Well, I wrote down that simple recursion based code:

>> Code

1-  def rec(memory=[], x=2):
2-      print(memory, x)
3-      if x > 0:
4-          memory.append(x)
5-          x -= 1
6-          rec(memory=memory, x=x)
7-      else:
8-          memory=[]
9-          return 0
10- 
11- rec()
11- print("First call done.")
12- rec()

And expected something like that:

>> Desired output

[] 2
[2] 1
[2, 1] 0
First call done.
[] 2
[2] 1
[2, 1] 0

But ended up by receiving that:

>> Real output

[] 2
[2] 1
[2, 1] 0
First call done.
[2, 1] 2
[2, 1, 2] 1
[2, 1, 2, 1] 0

Does someone know why the rec() function keeps hold of the memory even when I explicitly tell it to set memory back to an empty list in line 8? And... What do I have to do for it not to save the information across multiple function calls?

  • 3
    you're not setting it back to an empty list like you shown on line 8. that empty list ... `memory = []` is not being called back into the `rec()` function. if it fails the `if` check, it just returns 0. you would need to call `rec()` within that `else` scope then, for that list to be reset to empty. – de_classified Jun 07 '20 at 22:06

1 Answers1

1

Without explaining the inner workings, you might just do:

def rec(memory = [], x = 2):
    print(memory)
    if x:
        memory.append(x)
        x -= 1
        rec(memory = memory, x = x)
    else:
        del memory[:]
        return

rec()
print("First call done.")
rec()

---

[]
[2]
[2, 1]
First call done.
[]
[2]
[2, 1]
misantroop
  • 2,276
  • 1
  • 16
  • 24