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

Stefan Behnel stefan_ml at behnel.de
Fri Sep 4 13:12:02 CEST 2009


Jan Kaliszewski wrote:
> 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")

or:

     def getany(container):
         for x in container:
             return x
         raise ValueError("No items in container")

I actually like that, although I find this more readable:

     def getany(container):
         for x in container:
             return x
         else:
             raise ValueError("No items in container")

Stefan




More information about the Python-ideas mailing list