1

Currently, I implement a for loop as a recursive method.

for i in range(len(list)):
   **implementation code goes here**

how do I implement this as a recursive method?

I am planning on going through a list, checking if each item is in another list of accepted possible values. If so, I do certain actions on it. Else, I do other actions.

8
  • I just edited it now. :) Commented Oct 20, 2012 at 3:38
  • Yeah, I changed the question too. LOL Commented Oct 20, 2012 at 3:39
  • What are you planning on doing in the loop? It doesn't really make sense to recurse if you're not doing anything ... Commented Oct 20, 2012 at 3:40
  • Just to confirm I am considering only 1 loop - Just making that clear. Commented Oct 20, 2012 at 3:40
  • Then what do you want to do in that loop.? We can't convert until we know what that loop is for. Commented Oct 20, 2012 at 3:40

2 Answers 2

5

The standard structural recursive formula (and the one you'd use if you were using a functional language like Scheme) would be to deconstruct the list recursively:

func([]) => nothing
func([x, ...]) => do_stuff(x), func([...])

Therefore, the "functional" way to do this would be to take a single list (not an index), and to recurse on smaller lists:

def rec_list(l):
    if not l: return # empty list case
    # process l[0]
    return rec_list(l[1:])

Note that this is terribly, terribly inefficient because of the l[1:], but it's the basis for understanding more complex recursive constructs (e.g. recursing on binary trees).

We can do interesting things with this kind of structural recursion. For example, here's how you'd reverse a list in a functional language:

def rev_list(l):
    if not l: return []
    return rev_list(l[1:]) + [l[0]]

(Of course, you could just do l[::-1] in Python, but here we're trying to show how it would be done recursively).

Sign up to request clarification or add additional context in comments.

3 Comments

I wonder if it would be worth creating a "sliced sequence" class in order to support this efficiently...
Note that this recursively iterates over the items in the list, not the indices as the OP's code example. However, it's a very nice explanation (I don't use functional languages much myself, so it's interesting to see a new way to do these things). +1 from me.
@IgnacioVazquez-Abrams: I've always thought it would be a nice feature to have in Python, though adding too many "lazy" features might get a bit complicated. Numpy's array does have lazy slicing (l[1:] returns a view), so you could use that.
1

So you want to do away with a nice (mostly) well coded loop? (mostly because you probably want to use enumerate instead of range(len(lst))) -- enumerate is pretty cool, once you start using it, you'll never look back.

Anyway, I guess we can do that:

def silly_loop(lst,index=0):
    try:
       #do something with index and lst here
       silly_loop(lst,index=index+1)
    except IndexError:  #or maybe a different error, depending on what you're doing with index ...
       return

an example:

def silly_loop(lst,index=0):
    try:
       print lst[index]
       silly_loop(lst,index=index+1)
    except IndexError:
       return

a = range(10)
silly_loop(a)

Note that I can't think of ANY reason why you would want to do this in real code, (But, if you're just doing this to teach yourself about recursion, then I hope this helps).

2 Comments

I think it's pretty obvious that this is a learning exercise. There is no reason to be so patronising either.
@QuickJoeSmith -- I'm not trying to be patronizing. It's not obvious that this is just a learning exercise. I've seen a lot of requests from people trying to do some pretty strange things because they didn't know better. (Perhaps they read about how awesome recursion is and they thought it would solve all their problems ...) I wrote the post this way to make sure that OP understands that this is not idiomatic python and shouldn't be used in real code. In any event, you might be right that I might have overdone it. I've tried to soften it up a little bit. Do you think it's any better?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.