Python len() 内置函数

来自 Python 3 文档

返回对象的长度(项数)。参数可以是序列(如字符串、字节、元组列表范围)或集合(如字典集合冻结集合)。

简介

Python 中的 len() 函数是一个内置函数,用于返回对象中的项数(长度)。该对象可以是序列(如字符串、列表、元组)或集合(如字典或集合)。

示例

返回对象的项数:

len('hello')
len(['cat', 3, 'dog'])
5
3

判空测试

判空测试

字符串、列表、字典等的判空测试不应使用 len,而应优先使用直接的布尔值评估。

a = [1, 2, 3]

# 差
if len(a) > 0:  # 评估为 True
    print("the list is not empty!")

# 好
if a:  # 评估为 True
    print("the list is not empty!")
the list is not empty!
the list is not empty!

相关链接