深度阅读

How to use the len() function in Python

作者
作者
2023年08月22日
更新时间
7.77 分钟
阅读时间
0
阅读量

To use the len() function in Python, you simply pass an object as an argument, and len() will return the number of items in that object. Here are some examples:

Getting the length of a string:

s = "Hello, world!"
length = len(s)
print(length)  # output: 13

Getting the length of a list:

my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length)  # output: 5

Getting the length of a dictionary:

my_dict = {"a": 1, "b": 2, "c": 3}
length = len(my_dict)
print(length)  # output: 3

Note that the len() function only works with objects that have a defined length, such as strings, lists, and dictionaries, among others. If you try to use len() with an object that doesn’t have a defined length, you’ll get a TypeError exception.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。