You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中为何[] and {}返回[]?空列表与空字典为何为假值?

Understanding [] 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 None value
  • 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 {}:

  1. First operand is [], which is falsy
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:03:20