Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this Python boolean comparison return a triple?

I was playing around on the command-line for Python 2.7.8, where I encountered this behavior:

>>> "902".isdigit() == True
True
>>> "902".isdigit(), "2".isdigit() == True
(True, True)
>>> "902".isdigit(), "2".isdigit() == True,True
(True, True, True)
>>> ("902".isdigit(), "2".isdigit()) == (True,True)

I found this surprising. I would have expected >>> "902".isdigit(), "2".isdigit() == True,True to simply return True as if I had surrounded both expressions in parentheses to make them into tuples. Why does Python return this tuple of booleans, rather than a single one? What boolean comparisons does this tuple represent?

like image 877
Newb Avatar asked Mar 27 '26 19:03

Newb


2 Answers

Because:

"902".isdigit(), "2".isdigit() == True,True

is interpreted as:

("902".isdigit(), ("2".isdigit() == True), True)

Note that you shouldn't test booleans with ==; a more pythonic way to write the test is:

"902".isdigit() and "2".isdigit()
like image 145
jonrsharpe Avatar answered Mar 29 '26 07:03

jonrsharpe


To add to jonrsharpe's answer:

The reason it is interpreted this way is because the Python parser has no way to determine whether:

 "902".isdigit(), "2".isdigit() == True, True

was meant to be:

("902".isdigit(), ("2".isdigit() == True), True)

or:

("902".isdigit(), "2".isdigit()) == (True, True)

Basically there is no way to (from a grammar perspective) to determine this without using explicit parentheses.

See: Full Grammar Specification (but you'd need some background in BNF/EBNF grammars).

like image 25
James Mills Avatar answered Mar 29 '26 08:03

James Mills