Counting the number of elements in a list - help.

Jeff Shannon jeff at ccvcorp.com
Thu Apr 18 15:32:13 EDT 2002


In article <a9hu8e$2fg$1 at lumberjack.rand.org>, bmason at rand.org 
says...
> I need to know these things; may someone help me out?
> 
> 1) a function which returns the number of elements in a list
> 2) a function which takes a list and an index and returns a zero when that
> list index is out of range.

It seems that your problem has been solved, but... just 'cause...

Your second function could easily be written like this:

def InRange(sequence, index):
    try:
        sequence[index]
    except IndexError:
        return 0
    else:
        return 1

(Note that the 'return 1' isn't strictly required to be in an 
else: clause here, but I think that using else, in this case, is 
a clearer expression of intent.)

-- 

Jeff Shannon
Technician/Programmer
Credit International



More information about the Python-list mailing list