Python "maximum recursion depth exceeded in comparison" with variable arguments. Works fine with lists, however

StackOverflow https://stackoverflow.com/questions/23158000

Question

I have the following function:

def lst(*l):
  if l==():return None
  else: return cons(l[0],lst(l[1:]))

When I run it, I get "maximum recursion depth exceeded in comparison". Curiously, when I add a warper which converts the parameter tuple into a list, everything works just fine:

def lst(*l):
  return _lst(list(l))

def _lst(l):
  if l==[]:return None
  else: return (l[0],_lst(l[1:]))

>>> lst(1,2)
(1, (2, None))

What is the problem and how to deal with this strange behavior?

Was it helpful?

Solution

you are missing a * when passing the parameters again to the function

def lst(*l):
  if l==():return None
  else: return cons(l[0],lst(*l[1:]))

You are passing the empty tuple as a first positional parameter which means that in the next recursion l is actually equal to ((),) (a tuple containing one empty tuple) when it should be ()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top