Search code examples
pythonlispcons

LISP cons in python


Is there an equivalent of cons in Python? (any version above 2.5)

If so, is it built in? Or do I need easy_install do get a module?


Solution

  • In Python, it's more typical to use the array-based list class than Lisp-style linked lists. But it's not too hard to convert between them:

    def cons(seq):
        result = None
        for item in reversed(seq):
            result = (item, result)
        return result
    
    def iter_cons(seq):
        while seq is not None:
            car, cdr = seq
            yield car
            seq = cdr
    
    >>> cons([1, 2, 3, 4, 5, 6])
    (1, (2, (3, (4, (5, (6, None))))))
    >>> iter_cons(_)
    <generator object uncons at 0x00000000024D7090>
    >>> list(_)
    [1, 2, 3, 4, 5, 6]