[Python-ideas] 1 + True = 2

Chris Angelico rosuav at gmail.com
Sun Jun 5 12:48:50 EDT 2016


On Mon, Jun 6, 2016 at 2:37 AM, Giampaolo Rodola' <g.rodola at gmail.com> wrote:
>>>> 1 + True
> 2
>>>> 1 + False
> 1
>>>>
>
> I bumped into this today by accident and I can't recall ever being aware of
> this. Why isn't this a TypeError in Python 3?
>

Because it's a good thing. bool is a subclass of int, True is exactly
1, False is exactly 0. You can sum a series of conditions and get the
number that are true, for instance. There's no point doing this:

sum(1 if x < 5 else 0 for x in stuff)

when you can just do this:

sum(x < 5 for x in stuff)

to quickly count the values that fit some condition.

ChrisA


More information about the Python-ideas mailing list