Python len() Function

Returns the number of items of an object

Usage

The len() function returns the number of items of an object.

The object may be a sequence (such as a string, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

Syntax

len(object)

Python len() function parameters
ParameterConditionDescription
objectRequiredA sequence or a collection.

len() on Sequences

Example: Find the number of characters in a string

S = 'Python'
x = len(S)
print(x)  # 6

Example: Find the number of items in a list

L = ['red', 'green', 'blue']
x = len(L)
print(x)  # 3

Example: Find the number of items in a tuple

T = ('red', 'green', 'blue')
x = len(T)
print(x)  # 3

len() on Collections

Example: Find the number of key:value pairs in a dictionary

D = {'name': 'Bob', 'age': 25}
x = len(D)
print(x)  # 2

Example: Find the number of items in a set

S = {'red', 'green', 'blue'}
x = len(S)
print(x)  # 3