How to use the len function in Python

小老鼠
Release: 2023-12-18 14:53:32
Original
1862 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!