Home  >  Article  >  Backend Development  >  Python's len() function: Get the length of a list or string

Python's len() function: Get the length of a list or string

WBOY
WBOYOriginal
2023-11-18 09:23:281335browse

Pythons 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

  1. Get the length of the string:
str1 = "Hello World!"
length = len(str1)
print("字符串的长度为:", length)

Output:

字符串的长度为: 12
  1. Get the length of the list Length:
lst = [1, 2, 3, 4, 5]
length = len(lst)
print("列表的长度为:", length)

Output:

列表的长度为: 5
  1. Get the length of the tuple:
tpl = (1, 2, 3, 4, 5)
length = len(tpl)
print("元组的长度为:", length)

Output:

元组的长度为: 5

Four , Notes

  1. The len() function returns an integer, indicating the length of the object. This length is based on the number of properties or elements of the object.
  2. For container objects, such as lists, tuples, etc., the len() function returns the number of elements they contain.
  3. For string objects, the len() function returns the number of characters in the string.
  4. If the object passed to the len() function is None, a TypeError exception will be thrown.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Related articles

See more