illuminato
illuminato

Reputation: 1257

Confusion with lists and recursion

First, let me give you an example that I do understand:

def f(i):
    l.append(i)
    if i == 1:
        return
    
    f(i+1)
    
    return l 
l = [1,2,3]
f(0)

Output is

[1, 2, 3, 0, 1]

And it is consistent with what I know. Even if you don't specify the list explicitly in functional call (e.g f(i,l)) you still can use and change this list in a function.

And here is an example that I don't understand:

def f(i):
    l = []
    l.append(i)
    print(l)
    if i == 1:
        return
    
    f(i+1)
    
    return l
f(0)

Output is:

[0]
[1]
[0]

So in first functional call f(0) we create list and append 0 to the list (list == [0]). Next, we have recursion f(1) where we recreate the list so the list with [0] has gone and 1 was appended (list == [1]). We go to if i == 1: statement and getting return from f(i+1). But for some reason, that I don't understand, the final output is [0]. It is very confusing. Our recursion call (f(i+1)) should change the list. And I demonstrated in the first example that python should honor any changes in a list.

Why is output [1] and not [0]?

Upvotes: 0

Views: 66

Answers (1)

J.Arranz
J.Arranz

Reputation: 361

It seems that you have problems with list variable scope. In your first example list variable is outer of "f" method, which means that list can be appended in every recursive iteration due to list object is the same.

In second example list variable has inner scope. That means new list object is created in every recursive iteration. When your code finished, list value is the first value it caught when "f" was called.

You could include list parameter in recursion calls, something like that:

def f(i, l):
   l.append(i)
   print(l)
   if i == 1:
      return

   f(i+1, l)
   return l

f(0, list())

Upvotes: 1

Related Questions