Python len() Function: Complete Guide

The len() function is used to return the length or number of elements in an object. Its syntax is:

len(object)

object represents the object from which the length is to be retrieved and can be a string, list, tuple, dictionary, etc.

For example, obtaining the length of a string:

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

Get the length of the list.

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

Obtain the number of key-value pairs in the dictionary:

my_dict = {"a": 1, "b": 2, "c": 3}
length = len(my_dict)
print(length)  # 输出:3
bannerAds