Counting the number of elements in a list - help.
Christophe Delord
christophe.delord at free.fr
Thu Apr 18 15:54:24 EDT 2002
On Thu, 18 Apr 2002 12:32:13 -0700
Jeff Shannon <jeff at ccvcorp.com> wrote:
It could be shorter and smarter like this :
def InRange(sequence, index):
return 0 <= index < len(sequence)
> 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
--
Christophe Delord
http://christophe.delord.free.fr/
More information about the Python-list
mailing list