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

Patricia Arquette
Release: 2024-11-01 04:23:02
Original
952 people have browsed it

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)
Copy after login

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
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!