Teaching : Python, Scheme, Java...

Robin Munn rmunn at pobox.com
Mon Apr 21 17:40:22 EDT 2003


Andrew Bennetts <andrew-pythonlist at puzzling.org> wrote:
> On Thu, Apr 17, 2003 at 09:55:46AM +0200, Jean-Paul Roy wrote:
> [..]
>> Aside from that points, a personal question as a Schemer who reads the 
>> Python primer:
[snip one question]
>> - how do you ask if the list has only one element, with time 0(1) ? The
>>   Scheme/Lisp analog is (null? (cdr L))
> 
> len(L) == 1
> 

List length is cached with the list object, so this is indeed O(1).
Another way would have been:

    try:
        L[1]
    except IndexError:
        print "L has at most one element"

Note that this will not tell you whether the list has exactly one
element, so it answers a slightly different question. But it's always
useful to know of different ways of solving a problem.

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838




More information about the Python-list mailing list