ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> python-dev
python-dev
Re: [Python-Dev] Retrieve an arbitrary element from asetwithoutremoving it
by Raymond Hettinger other posts by this author
Nov 5 2009 3:03PM messages near this date
Re: [Python-Dev] Status of the Buildbot fleet and related bugs | Re: [Python-Dev] Retrieve an arbitrary element from asetwithoutremoving it
[me]
>  Why not write a short, fast get_first() function for your utils directory and be done with
 it?
>  That could work with sets, mappings, generators, and other containers and iterators.
>  No need to fatten the set/frozenset API for something so trivial and so rarely needed.

Forgot to post the code.  It is short, fast, and easy.  It is explicit about handing the cas
e with an empty input.  And it is 
specific about which value it returns (always the first iterated value; not an arbitrary one
).  There's no guessing about what it 
does.  It gets the job done.

def first(iterable):
    'Return the first value from a container or iterable.  If empty, raises LookupError'
    for value in iterable:
        return value
    raise LookupError('no first value; iterable is empty')

If desired, it is not hard to change to the last time to return a default value or some othe
r exception.


Raymond



_______________________________________________
Python-Dev mailing list
Python-Dev@[...].org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: http://mail.python.org/mailman/options/python-dev/python-dev-ml%40maillist.acti
vestate.com
Thread:
Raymond Hettinger
bjourne
Steven D'Aprano
martin
Nick Coghlan
Daniel Stutzbach
martin
Daniel Stutzbach
martin
Alexander Belopolsky
Nick Coghlan
Nick Coghlan
martin
Daniel Stutzbach
Chris Bergstresser
martin
Chris Bergstresser
Georg Brandl

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved