c enum - how to do this in python?

Gerhard =?unknown-8bit?Q?H=E4ring?= gerhard.haering at gmx.de
Sat Feb 22 09:30:57 EST 2003


* Anna <revanna at mn.rr.com> [2003-02-22 14:01 +0000]:
> On Sat, 22 Feb 2003 07:50:16 +0000, Alex Martelli wrote:
> > def lastone(somelist, condition):
> >     for item in somelist[::-1]:
> >         if condition(item): return item
> >     raise ValueError, "No item matches the condition"
> 
> Can't you do:
> 
> def lastone(somelist, condition):
>      for item in somelist.reverse():
>          if condition(item): return item
>      raise ValueError, "No item matches the condition"
> 
> Wouldn't that do the same thing?

Unfortunately not, because .reverse() on a list doesn't return the
reversed list. So you'd have to do it in two steps:

#v+
def lastone(somelist, condition):
    tmplist = somelist[:]       # Make a copy of the list
    tmplist.reverse()
    for item in tmplist:
        ...
#v-

Making a copy of the list is of course only required if you want to keep
the original 'somelist' unchanged.

Iterating over a list in reverse order is also covered in the Python
FAQ: http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.006.htp

Btw. I'd recommend to take a look over the entire FAQ once, because most
of the surprising behaviour of Python (just like list methods like
.reverse() or .append() not returning the changed list) are covered
there. This will spare you unpleasant bug hunting later on.

Have fun,

Gerhard
-- 
Favourite database:             http://www.postgresql.org/
Favourite programming language: http://www.python.org/
Combine the two:                http://pypgsql.sf.net/
Embedded database for Python:   http://pysqlite.sf.net/





More information about the Python-list mailing list