[Python-ideas] data structures should have an .any() method

Jan Kaliszewski zuo at chopin.edu.pl
Fri Sep 4 12:32:05 CEST 2009


04-09-2009 Nick Coghlan <ncoghlan at gmail.com> wrote:

> def getany(container)
>   if container:
>     if isinstance(container, collections.Sequence):
>       return container[0]
>     else:
>       for x in container:
>         return x
>   raise ValueError("No items in container")

or simpler:

     def getany(container):
         try:
             return next(iter(container))
         except StopIteration
             raise ValueError("No items in container")

-- 
Jan Kaliszewski (zuo) <zuo at chopin.edu.pl>



More information about the Python-ideas mailing list