Home >Backend Development >Python Tutorial >Why Does `0 < 0 == 0` Evaluate to `False` in Python?

Why Does `0 < 0 == 0` Evaluate to `False` in Python?

DDD
DDDOriginal
2024-12-09 03:27:12754browse

Why Does `0 < 0 == 0` Evaluate to `False` in Python?

Chained Comparisons in Python: Unraveling the Mystery of 0 < 0 == 0 Falsehood

In the depths of Python's standard library code, lies a puzzling construct in Queue.py from Python 2.6:

def full(self):
    """Return True if the queue is full, False otherwise
    (not reliable!)."""
    self.mutex.acquire()
    n = 0 < self.maxsize == self._qsize()
    self.mutex.release()
    return n

Why does this expression, 0 < 0 == 0, yield False? At first glance, it seems counterintuitive, as 0 is clearly less than 0, and 0 == 0 is True.

Chained Comparisons: Python's Shortcut

Python has a unique feature called "chained comparisons," which makes expressing range comparisons more concise. For example, the following is equivalent to using chained comparisons:

0 < x <= 5

Internally, these chained comparisons are interpreted differently. Python evaluates the expression from left to right and returns the value of the first comparison that evaluates to False. In our case, 0 < 0 evaluates to False, so the subsequent == 0 evaluation is irrelevant and thus the expression returns False.

In contrast, when parentheses are introduced, they force the evaluation of the expression within them to be completed before the next comparison is applied. This negates the chained comparison behavior. As a result, we get the expected True values when parentheses are added:

(0 < 0) == 0
0 < (0 == 0)

Therefore, the full() method's expression, 0 < self.maxsize == self._qsize(), evaluates to False if self.maxsize is 0, indicating that the queue is never full when the size limit is set to 0.

The above is the detailed content of Why Does `0 < 0 == 0` Evaluate to `False` in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn