A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2009-November/093818.html below:

[Python-Dev] Retrieve an arbitrary element from asetwithoutremoving it

[Python-Dev] Retrieve an arbitrary element from asetwithoutremoving it [Python-Dev] Retrieve an arbitrary element from asetwithoutremoving itRaymond Hettinger python at rcn.com
Fri Nov 6 00:02:01 CET 2009
[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 case 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 other exception.


Raymond



More information about the Python-Dev mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4