📜  如何在 python 中获取列表的大小(1)

📅  最后修改于: 2023-12-03 15:24:20.156000             🧑  作者: Mango

如何在 Python 中获取列表的大小

在 Python 中获取列表的大小,可以使用内置函数len()。使用len()函数,返回的是列表中元素的个数,也就是列表的长度。

以下是一个示例代码:

my_list = [1, 2, 3, 4, 5]
list_size = len(my_list)
print(f"The size of the list is {list_size}")

代码输出:

The size of the list is 5

此外,还可以通过迭代列表中的元素,来获取列表的大小。以下是一个示例代码:

my_list = [1, 2, 3, 4, 5]
list_size = 0

for item in my_list:
    list_size += 1

print(f"The size of the list is {list_size}")

代码输出:

The size of the list is 5

我们可以看到,使用len()函数和使用迭代,都可以得到相同的结果。但是,使用len()函数更为简单和高效,所以我们通常会选择使用len()函数。