and — Intermediate Examples
Logical AND operator; returns True if both operands are true
Short-circuit evaluation
How 'and' stops at the first falsy value.
python
# and returns the first falsy value, or the last value print(1 and 2 and 3) # All truthy -> last value print(1 and 0 and 3) # 0 is falsy -> returns 0 print("" and "hello") # "" is falsy -> returns "" print("hi" and "hello") # Both truthy -> "hello" # Practical: guard before access data = {"users": [{"name": "Alice"}]} users = data.get("users") if users and len(users) > 0 and users[0].get("name"): print(f"First user: {users[0]['name']}") # and as a conditional expression debug = True message = debug and "Debug mode ON" print(message)
Expected Output
3 0 hello First user: Alice Debug mode ON
'and' short-circuits: it evaluates left to right and returns the first falsy value (or the last value if all are truthy). This makes guard patterns safe.
and with different types
Understanding truthiness in and expressions.
python
# and with non-boolean types print([] and "hello") # [] is falsy print([1] and "hello") # [1] is truthy, returns "hello" print(None and 42) # None is falsy print({"a": 1} and "yes") # dict is truthy # Chained comparison (Python sugar) x = 5 # These are equivalent: print(1 < x < 10) # Python chained comparison print(1 < x and x < 10) # Explicit and # All truthy check values = [1, "hello", [1], True] if all(values): print("All values are truthy")
Expected Output
hello None yes True True All values are truthy
Python's chained comparisons like '1 < x < 10' are syntactic sugar for '1 < x and x < 10', but x is only evaluated once.
Want to try these examples interactively?
Open Intermediate Playground