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

Masklinn masklinn at masklinn.net
Fri Sep 4 11:48:43 CEST 2009

On 4 Sep 2009, at 11:35 , Stefan Behnel wrote:
> 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.
Given the random value you want from the dict is a key, how about  
`random.choice(list(container))` (list is needed because choice works  
on sequences)?

 >>> l, s, d
([0, 1, 2, 3, 4], set([8, 9, 5, 6, 7]), {10: 15, 11: 16, 12: 17, 13:  
18, 14: 19})
 >>> choice(list(l))
 >>> choice(list(s))
 >>> choice(list(d))

More information about the Python-ideas mailing list