Comparisons and truthiness in Python
Chained comparisons, identity against equality, and what counts as false.
x = 7
print(0 < x < 10, x != 3 == 3)
a, b = [1, 2], [1, 2]
print(a == b, a is b, a is a)
print(None is None, 1 == 1.0, 1 is 1.0)
for value in (0, "", [], {}, None, 0.0, "0", [0]):
print(repr(value), bool(value))
How it works
0 < x < 10evaluates x once and reads like maths.iscompares identity; use==for value.- Empty containers, zero and None are all falsy.
Keywords and builtins used here
boolforprintrepr
The run, in numbers
- Lines
- 9
- Characters to type
- 213
- Tokens
- 100
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 60 seconds.
Step 3 of 3 in Expressions, step 67 of 72 in Language basics.