Python中为何[] and {}返回[]?空列表与空字典为何为假值?
[] and {} in Python & Why Empty Containers Are Falsy Hey there! Let's unpack this confusion step by step—since you already grasp the core logic of and/or, the key here is two Python-specific behaviors you might not have fully connected yet.
1. Why empty lists [] and empty dictionaries {} are falsy
In Python, "truthiness" isn't limited to True and False values. The language defines a set of values that are considered falsy (evaluate to False in a boolean context):
- Empty sequences:
[](list),()(tuple),""(string) - Empty mappings:
{}(dictionary) - Numeric zeros:
0,0.0,0j - The
Nonevalue - Explicit
False
You can test this directly with the bool() function:
>>> bool([]) False >>> bool({}) False
This is a design choice to make common checks (like "is this list empty?") more concise—you can write if not my_list: instead of if len(my_list) == 0:.
2. How and actually returns values (not just True/False)
You know that and requires both operands to be truthy for the result to be truthy, but here's the critical detail: Python's and operator returns the actual operand value, not a converted boolean. The rule is:
- If the first operand is falsy, return the first operand (short-circuit evaluation—no need to check the second)
- If the first operand is truthy, return the second operand
So let's apply this to [] and {}:
- First operand is
[], which is falsy - Python short-circuits and returns
[]immediately, never evaluating the{}
To contrast, here are a few examples to drive this home:
# First operand is truthy, returns the second >>> [1,2] and {} {} # First operand is falsy, returns it >>> {} and [] {} # Or operator works similarly but picks the first truthy value >>> [] or {} {}
That's all there is to it! The combination of empty containers being falsy and Python's and returning operand values instead of booleans explains the behavior you're seeing.
内容的提问来源于stack exchange,提问作者my-lord

