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

Matteo Dell'Amico matteodellamico at gmail.com
Fri Sep 4 11:55:05 CEST 2009


Stefan Behnel ha scritto:
> Hi,
> 
> I just had a discussion with a co-worker, and we noticed that there are use
> cases where you just want the only element in a data structure, or just any
> of the elements in a data structure because you know that they all contain
> the same information (with respect to what you are looking for, at least).
> 
> If you want all items, you can iterate, but if you just want any item or
> the only item, it's inefficient (and not very explicit code) to create an
> iterator and take the element out. It's easy to do with ordered data
> structures such as lists or tuples ("container[0]"), but it's not so
> obvious for sets (or dicts), which means that you have to know what kind of
> container you receive to handle it correctly. I know there's .pop() on
> sets, but that modifies the data structure.

You can do next(iter(container)) (or iter(container).next() with python 
<= 2.5). This works fine with any iterable.

matteo



More information about the Python-ideas mailing list