Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 774
valplo Avatar asked Nov 27 '25 07:11

valplo


1 Answers

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 ()

like image 74
Samy Arous Avatar answered Nov 28 '25 22:11

Samy Arous