python list handling and Lisp list handling

Mark Wooding mdw at distorted.org.uk
Sat Apr 25 21:30:17 EDT 2009


Mark Tarver <dr.mtarver at ukonline.co.uk> writes:

> But are Python lists also indistinguishable from conventional
> Lisplists for list processing. 
>
> For example, can I modify a Python list non-destructively?  

No.

> Are they equivalent to Lisp lists. Can CAR and CDR in Lisp be thought
> of as
>
> def car (x):
>   return x[0]
>
> def cdr (x):
>   return x[1:]

Not in the presence of side-effects, no.

The slice-extration operation on lists constructs a copy of the
original, and mutating the original doesn't affect the copy.  Here's a
simple example.

[Load your definitions...]

In [1]: def car (x): return x[0]
   ...:

In [2]: def cdr (x): return x[1:]
   ...:

[Python]                           [Common Lisp]

In [3]: a = [1, 2, 3, 4]           CL-USER> (setf a (list 1 2 3 4))
                                   (1 2 3 4)

In [4]: b = cdr(a)                 CL-USER> (setf b (cdr a))
                                   (2 3 4)

In [5]: a[2] = 'banana'            CL-USER> (setf (third a) "banana")
                                   "banana"

In [6]: a                          CL-USER> a
Out[6]: [1, 2, 'banana', 4]        (1 2 "banana" 4)

In [7]: b                          CL-USER> b
Out[7]: [2, 3, 4]                ! (2 "banana" 4)

Also, note:

In [8]: b is cdr(a)                CL-USER> (eq b (cdr a))
Out[8]: False                    ! T

Your Python `cdr' operation conses.  Until you create it explicitly,
there is no Python value corresponding to `all but the first element of
this list'.

But, apart from the performance and sharing characteristics, they're the
same.  I think those are pretty big differences, though.

-- [mdw]



More information about the Python-list mailing list