[Tutor] Recursion help

Zak Arntson zak@harlekin-maus.com
Thu Jul 31 18:22:15 2003


> I am working thru some of the examples in the "Learning to Program"
> tutorial. I am going thru the recusrion section and have gotten stumped.
> Here is the code I have run below:
>
> def printList(L):
>     # if its empty do nothing
>     if not L: return

Reexamine this if statement. What will the type of L[0] be?

>     # if its a list call printList on 1st element
>     if type(L[0]) == type([]):
>         printList(L[0])
>     else: #no list so just print
>         print L[0]
>     # now process the rest of L
>     printList(L[1:])
>
> It "appears" that the code is running thru the else block over and over
> until it reaches the end of the list. However, I do not see how the list
> is being enumerated or how it knows to go to the next item in the list.
> Can anyone shed some light on this?

You can look at it this way:
printList((1,2,3))
   prints (1,2,3)[0] which is 1
   runs printList((1,2,3)[1:]) = printList((2,3))
   now we're in printList((2,3))
      prints (2,3)[0] which is 2
      runs printList((2,3)[1:]) and so on ...

>
> Thanks,
> Justin

---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em