How to use the len function in Python
In Python, the len() function is used to retrieve the length or number of elements in an object (such as a list, tuple, string, etc.).
syntax:
len(obj)
Parameter:
obj: The object for which to retrieve the length or count.
Return value:
The length or number of objects returned.
原文:我昨天看了一部很有趣的电影。
Paraphrased: Yesterday, I watched a very interesting movie.
- Get the length of the string:
s = "Hello World"
print(len(s)) # 输出:11
- Get the length of the list.
lst = [1, 2, 3, 4, 5]
print(len(lst)) # 输出:5
- Get the length of a tuple:
tpl = (1, 2, 3, 4, 5)
print(len(tpl)) # 输出:5
- Get the length of the dictionary (returns the number of keys):
dct = {"name": "Alice", "age": 20, "gender": "female"}
print(len(dct)) # 输出:3
It is important to note that the len() function can only be used on objects that can calculate length or count. If an object that does not support length or count calculation is passed in, a TypeError exception will be raised.