len() 函数在 Python 中用于计算可迭代对象中的元素数量。使用方法:将可迭代对象作为参数传递,函数将返回对象中元素的数量。对象类型包括字符串、列表、元组、字典和集合。

len() 函数在 Python 中的用法
Python 的 len() 函数用于获取可迭代对象中元素的数量。它可以应用于字符串、列表、元组、字典和集合等多种数据类型。
语法
len(object)
其中:
立即学习“Python免费学习笔记(深入)”;
-
object是要计算其长度的可迭代对象。
使用方法
要使用 len() 函数,只需将可迭代对象作为参数传递给它。函数将返回对象中元素的数量。
示例
- 字符串
my_string = "Hello World" string_length = len(my_string) # 值为 11
- 列表
my_list = [1, 2, 3, 4, 5] list_length = len(my_list) # 值为 5
- 元组
my_tuple = (1, 2, 3, 4, 5) tuple_length = len(my_tuple) # 值为 5
- 字典
my_dict = {"name": "John", "age": 30}
dict_length = len(my_dict) # 值为 2- 集合
my_set = {1, 2, 3, 4, 5}
set_length = len(my_set) # 值为 5在这些示例中,len() 函数返回了可迭代对象中包含的元素数量。











