0

I'm currently learning Python and recursive function. I'm just stuck with it that do not actually know what happened after the recursive step is executed. I have an example such

# sum of list
def my_sum(L):
   # this step is just print out current list 
   # at each level
   print(L)
   if not L:
      return 0
   else:
      return L[0] + my_sum(L[1:])

and the result for the above function is

[1,2,3,4,5]
[2,3,4,5]
[3,4,5]
[4,5]
[5]
[]
15

I've read a few articles about recursion and understood a bit. However, in this case, I don't see that size of L is decreased at all, so how can the list is growing smaller like that?

Could someone figure this out for me?

Thank you!

frankiie
  • 456
  • 1
  • 6
  • 19
  • I understand Python slice notation, and not asking about Python slice notation at all! Thanks. – frankiie Jan 04 '21 at 12:10
  • @jonrsharpe the question is not about slice, it is about the square bracket notation when calling a recursive function. – Davin Tryon Jan 04 '21 at 12:12
  • 1
    `my_sum[1:]` *is* a slice, there's no special notation with square brackets for recursive function calls. Given that `my_sum` is a function, there'll just be a type error - I think you meant `my_sum(L[1:])`. Note you can [edit] to clarify. – jonrsharpe Jan 04 '21 at 12:14
  • Yes, that function currently throws: `TypeError: 'function' object is not subscriptable` – Davin Tryon Jan 04 '21 at 12:18
  • @jonrsharpe yeah, it is a slice I know. But in this case, what I'm trying to figure out is why the list growing smaller like that even the resize of L is not used in the recursive call. – frankiie Jan 04 '21 at 12:20
  • *"even the resize of L is not used in the recursive call"* - it *is*, the new, shorter sliced list is passed in the recursive call. – jonrsharpe Jan 04 '21 at 12:22
  • @DavinTryon sorry for the typing error! I've edited the code correctly. – frankiie Jan 04 '21 at 12:22
  • @jonrsharpe maybe I do not understand well how the slice works in the recursive call. Could you provide me any resources to read about it? – frankiie Jan 04 '21 at 12:31

1 Answers1

0

This code: L[1:] slices all but the first item from the array. This is where the array size is decreased.

It is equivalent to tail.

So in this example:

L[0] is head

L[1:] is tail

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132