For a homework question I want to print items from a list incrementing each item by one. I want to do this using recursion (ideally without mutating a list).
NB: I understand that recursion is not a standard solution in Python or any other language (I don't intend to use it in any real world Python implementations) but this is part the recursion section of a CS course.
I think this problem could be solved far more simply and in a more Pythonic way by using a simple
for n in p:
print n + 1
if len(p) == 0:
r = list(p)
print r.pop(0) + 1
def rec_increment(p): if len(p) == 0: return "" #If you return an empty string, you don't get the "None" printing at the end. else: #r = list(p) This is not necessary now. print p+1 #r.pop(0) + 1 Rather than pop, just index. return rec_increment(p[1:]) # Only recurse on the 2nd-nth part of the list print rec_increment([1,2,3,4]) # Note that you don't need to both "print" in the function *and* print the result of the function - you can pick which you want to do.