can Python be useful as functional?

Evan Klitzke evan at
Tue Sep 18 03:30:21 CEST 2007

On 9/17/07, Lorenzo Stella <lorestar at> wrote:
> Hi all,
> I haven't experienced functional programming very much, but now I'm
> trying to learn Haskell and I've learned that: 1) in functional
> programming LISTS are fundmental; 2) any "cycle" in FP become
> recursion.
> I also know that Python got some useful tool such as map, filter,
> reduce... so I told: "let's try some FP-style programming with
> Python!". I took a little example of Haskell:
>      listprimes :: Integer -> [Integer]
>      listprimes n = if n == 0 then sieve [2..] else sieve [2..(n-1)]
> where
>             sieve [] = []
>             sieve (p:xs) = p : sieve (filter (\x -> mod x p > 0) xs)
> and I tried to "translate" it in Python:
>      def sieve(s):
>          if s == []:
>              return []
>          else:
>              return [s[0]] + sieve(filter((lambda x: x % s[0] > 0),
> s[1:]))
>      def listprimes(n):
>          return sieve(range(2,n))
> These should be almost the same: listprimes actually lists prime
> integers up to n-1. The result is: Haskell implementation works well,
> maybe it's not the better way to do it, but it does what I wanted.
> Python implementation gives me
>      RuntimeError: maximum recursion depth exceeded in cmp
> My question is: how can we call a language "functional" if it's major
> implementation has a limited stack? Or is my code wrong?

Python does not optimize tail recursion. You can increase the maximum
recursion limit with sys.setrecursionlimit, but the code will still be

I am a fan of functional programming languages (including Haskell!),
but I wouldn't try to write functional code in Python -- the language
isn't optimized for this type of code, and the syntax it provides
isn't very elegant, compared to other functional languages. If you
want to write functional code, use a real functional language!

Evan Klitzke <evan at>

More information about the Python-list mailing list