Home  >  Article  >  Backend Development  >  Why does `(1 in [1,0] == True)` evaluate to `False` in Python?

Why does `(1 in [1,0] == True)` evaluate to `False` in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-01 04:23:02934browse

Why does `(1 in [1,0] == True)` evaluate to `False` in Python?

False Evaluation of (1 in [1,0] == True)

Unlike a typical programming language, Python evaluates expressions using comparison operator chaining. In the expression (1 in [1,0] == True), the operation is not parsed as expected.

The expression is actually interpreted as:

(1 in [1, 0]) and ([1, 0] == True)

This evaluation breaks down into:

  • (1 in [1, 0]): This evaluates to True because 1 is present in the list [1, 0].
  • ([1, 0] == True): This evaluates to False because [1, 0] is a list, not a boolean value.

The overall expression, therefore, evaluates to:

True and False = False

This unexpected result highlights the difference in Python's evaluation of expressions compared to other languages. To avoid confusion, use parentheses to specify the desired evaluation order:

(1 in [1,0]) == True # True

The above is the detailed content of Why does `(1 in [1,0] == True)` 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