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

Bruce Leban bruce at leapyear.org
Wed Apr 6 16:24:05 CEST 2011


Nope.

>>> c = Counter()
>>> c[0] = -1
>>> c.elements()
[]
>>> c.values()
dict_values([-1])
>>> any(c.values())
True  # FAIL
>>> any(True for i in c.elements())
False

--- Bruce
*New! *Puzzazz newsletter: http://j.mp/puzzazz-news-2011-04 including April
Fools!
*New!** *Blog post:
http://www.vroospeak.com/2011/04/march-gets-more-madness-next-year.html April
Fools!



On Wed, Apr 6, 2011 at 7:02 AM, cool-RR <cool-rr at cool-rr.com> wrote:

> 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/0060ca21/attachment.html>


More information about the Python-ideas mailing list