Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion with ternary operator 'hack' in Python

Tags:

Playing around in Python, I found that the following code works as I expected:

f = lambda S,b : (S if len(S)==b else f(S[1:],b))

From a list S, it will recursively drop the first element until the length of S equals b. For instance f([1,2,3,4,5,6],3) = [4,5,6].

However, much to my surprise the following solution, that uses the 'ternary hack' [a,b][c] instead of "b if c else a" (aka "c?b:a") does not work:

g = lambda S,b : (g(S[1:],b),S)[len(S)==b]

This will exceed maximum recursion depth.

Why doesn't this work?

(I know neither is an example of great coding style but that is beside the point now.)