Home  >  Article  >  Backend Development  >  What is the usage of len function in Python?

What is the usage of len function in Python?

DDD
DDDOriginal
2023-11-20 15:13:2111392browse

The python usage of len function is: 1. String, len() function returns the length of the string, that is, the number of characters; 2. List, len() function returns the number of items in the list, that is, the number of elements in it Number; 3. Tuple, the len() function returns the number of items of the tuple, that is, the number of elements in it; 4. Dictionary, the len() function returns the number of items of the dictionary, that is, the number of key-value pairs, etc.

What is the usage of len function in Python?

# Operating system for this tutorial: Windows 10 system, Dell G3 computer.

In Python, the len() function is used to return the length or number of items of an object (such as string, list, tuple, etc.).

The following are some example usages of the len() function:

String:

text = "Hello, World!"  
print(len(text))  # 输出:13

In this example, the len() function returns characters The length of the string "Hello, World!", that is, the number of characters.

List:

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

In this example, the len() function returns the number of items in the list [1, 2, 3, 4, 5], which is The number of elements.

Tuple:

my_tuple = (1, 2, 3)  
print(len(my_tuple))  # 输出:3

In this example, the len() function returns the number of items in the tuple (1, 2, 3), that is, the number of elements in it number.

Dictionary:

my_dict = {"apple": 1, "banana": 2, "orange": 3}  
print(len(my_dict))  # 输出:3

In this example, the len() function returns the dictionary {"apple": 1, "banana": 2, "orange": 3 }The number of items, that is, the number of key-value pairs in it.

Please note that the len() function works for most objects, but if the object is not iterable (such as integers, floating point numbers, etc.), it will cause a TypeError exception.

The above is the detailed content of What is the usage of len function in Python?. 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