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?
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?
You can quite trivially define a class that behaves much like
cons
:However this will be a very 'heavyweight' way to build basic data structures, which Python is not optimised for, so I would expect the results to be much more CPU/memory intensive than doing something similar in Lisp.
Note that Python's lists are implemented as vectors, not as linked lists. You could do
lst.insert(0, val)
, but that operation is O(n).If you want a data structure that behaves more like a linked list, try using a Deque.
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:WARNING AHEAD: The material below may not be practical!
Actually,
cons
needs not to be primitive in Lisp, you can build it with λ. See Use of lambda for cons/car/cdr definition in SICP for details. In Python, it is translated to:Now,
car(cons("a", "b"))
should give you'a'
.How is that? Prefix Scheme :)
Obviously, you can start building list using
cdr
recursion. You can definenil
to be the empty pair in Python.Note that you must bind variable using
=
in Python. Am I right? Since it may mutate the variable, I'd rather define constant function.Of course, this is not Pythonic but Lispy, not so practical yet elegant.
Exercise: Implement the List Library http://srfi.schemers.org/srfi-1/srfi-1.html of Scheme in Python. Just kidding :)
No.
cons
is an implementation detail of Lisp-like languages; it doesn't exist in any meaningful sense in Python.