Home >Backend Development >Python Tutorial >Python's len() function: Get the length of a list or string
Python's len() function: Get the length of a list or string, you need specific code examples
1. Introduction
In Python programming, len( ) function is a very commonly used built-in function, used to obtain the length of data types such as lists, tuples, and strings. This function is very simple and convenient and can help us process data more efficiently. This article will introduce the usage of len() function in detail and give some specific code examples.
2. Usage of len() function
The len() function is used to return the length of a given object. For strings, it returns the number of characters in the string. For iterable objects such as lists and tuples, it returns the number of elements in the object.
In Python, the syntax of the len() function is as follows:
len(object)
Among them, object represents the object whose length is to be obtained.
3. Code example
str1 = "Hello World!" length = len(str1) print("字符串的长度为:", length)
Output:
字符串的长度为: 12
lst = [1, 2, 3, 4, 5] length = len(lst) print("列表的长度为:", length)
Output:
列表的长度为: 5
tpl = (1, 2, 3, 4, 5) length = len(tpl) print("元组的长度为:", length)
Output:
元组的长度为: 5
Four , Notes
5. Summary
The len() function is a commonly used function in Python, used to obtain the length of strings, lists, tuples and other objects. It is very simple and convenient and can help us get the size of the object quickly. This article provides an introduction to the usage of the len() function and gives specific code examples. I hope this article can help readers better understand and use the len() function.
The above is the detailed content of Python's len() function: Get the length of a list or string. For more information, please follow other related articles on the PHP Chinese website!