How do you use the len function in Python?

The len() function is used to retrieve the length of sequences such as strings, lists, and tuples. It takes one parameter which is the sequence to calculate the length of, and returns the number of elements in the sequence.

Here is an example demonstrating the usage of the len() function:

# 计算字符串的长度
string = "Hello, World!"
length = len(string)
print(length)  # 输出:13

# 计算列表的长度
list_1 = [1, 2, 3, 4, 5]
length = len(list_1)
print(length)  # 输出:5

# 计算元组的长度
tuple_1 = (1, 2, 3, 4, 5)
length = len(tuple_1)
print(length)  # 输出:5

Please note that the len() function can only be used on objects of sequence type, and attempting to use it on other types of objects will raise a TypeError exception.

bannerAds