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

Stefan Behnel stefan_ml at behnel.de
Fri Sep 4 11:35:57 CEST 2009


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.

It would therefore be nice to have a common ".any()" method on data
structures that would just read an arbitrary item from a container.

Regarding the special (and probably minor use) case of dicts, I assume it
would return any key, so that you could get the value from the dict in a
second step if you want. Only returning the value would not easily get you
the key itself.


More information about the Python-ideas mailing list