Home  >  Article  >  Backend Development  >  How to use the len function in Python

How to use the len function in Python

小老鼠
小老鼠Original
2023-12-14 15:59:511895browse

The len() function in Python is used to return the length or number of elements of an object. The specific functionality depends on the type of object passed to the len() function. Detailed introduction: 1. For sequence types (such as strings, lists, tuples, byte objects, etc.), the len() function returns the number of elements in the sequence; 2. For mapping types (such as dictionaries), the len() function Returns the number of key-value pairs in the map; 3. For collection types (such as collections, frozen collections, etc.), the len() function returns the number of elements in the collection.

How to use the len function in Python

The operating system for this tutorial: Windows 10 system, Python version 3.11.4, Dell G3 computer.

In Python, the len() function is used to return the length or number of elements of an object. The specific functionality depends on the type of object passed to the len() function.

1. For sequence types (such as strings, lists, tuples, byte objects, etc.), the len() function returns the number of elements in the sequence.

s = "Hello"
print(len(s))  # 输出为 5
lst = [1, 2, 3, 4, 5]
print(len(lst))  # 输出为 5
tup = (1, 2, 3)
print(len(tup))  # 输出为 3

2. For mapping types (such as dictionary), the len() function returns the number of key-value pairs in the mapping.

d = {"a": 1, "b": 2, "c": 3}
print(len(d))  # 输出为 3

3. For collection types (such as collections, frozen collections, etc.), the len() function returns the number of elements in the collection.

s = {1, 2, 3, 4}
print(len(s))  # 输出为 4

In short, the len() function is used to obtain the length or number of elements of different types of data. It is a very commonly used built-in function in Python.

The above is the detailed content of How to use the 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
Previous article:What is the LEN function?Next article:What is the LEN function?