[Python-ideas] A meaningful `if counter:`

cool-RR cool-rr at cool-rr.com
Wed Apr 6 16:02:45 CEST 2011


On Wed, Apr 6, 2011 at 3:57 PM, Bruce Leban <bruce at leapyear.org> wrote:

> No it won't.
>
> >>> c = Counter()
> >>> c[0] = 1
> >>> c[None] = 2
> >>> c[''] = 3
> >>> list(c.elements())
> [0, '', '', '', None, None]
> >>> any(c.elements())
> False  # FAIL
>
> >>> any(True for i in c.elements())
> True
> >>> d = Counter()
> >>> any(True for i in d.elements())
> False
>
> --- Bruce
>

Nice catch Bruce.

I think that `any(counter.values())` is solid:

>>> from collections import Counter
>>> counter = Counter([0, '', '', '', None, None])
>>> counter
Counter({'': 3, None: 2, 0: 1})
>>> any(counter.values())
True
>>> any(Counter().values())
False



Ram.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110406/b49e1226/attachment.html>


More information about the Python-ideas mailing list