c enum - how to do this in python?
gerhard.haering at gmx.de
Sat Feb 22 15:30:57 CET 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:
def lastone(somelist, condition):
tmplist = somelist[:] # Make a copy of the list
for item in tmplist:
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
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.
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