How to Use len() in Python

Modified: | Tags: Python

In Python, the built-in len() function returns the length (the number of items) of objects of various types, such as lists and strings.

List length with len()

l = [0, 1, 2]

print(len(l))
# 3
source: len_usage.py

For more details, including handling two-dimensional lists (lists of lists), refer to the following article.

Tuple length with len()

t = (0, 1, 2)

print(len(t))
# 3
source: len_usage.py

Set length with len()

s = {0, 1, 2}

print(len(s))
# 3
source: len_usage.py

For more details on sets, refer to the following article.

Dictionary length with len()

d = {'key_0': 0, 'key_1': 1, 'key_2': 2}

print(len(d))
# 3
source: len_usage.py

String length (number of characters) with len()

s = 'abcde'

print(len(s))
# 5
source: len_usage.py

For more information on finding string lengths, especially how escape sequences and line breaks are handled, refer to the following article.

The special method __len__()

When len() is executed, it calls the special method __len__() of the object. len(x) is equivalent to x.__len__().

l = [0, 1, 2]

print(l.__len__())
# 3

s = 'abcde'

print(s.__len__())
# 5
source: len_usage.py

An error occurs when len() is used with an object that lacks a __len__() method. For example, built-in numeric types such as int and float, as well as bool, do not support len() and will result in an error.

i = 100

print(hasattr(i, '__len__'))
# False

# print(len(i))
# TypeError: object of type 'int' has no len()
source: len_usage.py

hasattr() is a built-in function that determines whether an object has the specified attribute or method.

Custom classes can define the __len__() method to specify how len() calculates their length. This method should return an integer of 0 or greater. For demonstration, it returns 100 here.

class MyClass:
    def __len__(self):
        return 100

mc = MyClass()

print(len(mc))
# 100
source: len_usage.py

Related Categories

Related Articles