Python len() 内置函数
简介
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!