Skip to main content

Python len() Function

The len() function returns the number of items in an object, i.e. the length of the object.

Syntax​

len(object)

len() Parameters​

Python len() function parameters:

ParameterConditionDescription
objectRequiredThe object for which the length is to be determined (a sequence or a collection)

len() Return Value​

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

danger

Failing to pass an argument or passing an invalid argument will raise a TypeError exception.

Examples​

Example 1: Length of a String using len() function​

Get the length of a string:

name = "Tutorial Reference"
print(len(name)) # Output: 18

output

18

Example 2: Length of a List using len() function​

Get the length of a list:

langs = ["Python", "JavaScript", "Rust"]
print(len(langs)) # Output: 3

output

3

Example 3: Length of a Dictionary using len() function​

Get the length of a dictionary:

student = {"name": "Tom", "age": 25, "grade": "A"}
print(len(student)) # Output: 3

output

3

Example 4: Length of a Tuple using len() function​

Get the length of a tuple:

coordinates = (40.689167,-74.044444)
print(len(coordinates)) # Output: 2

output

2

Example 5: Length of a Set using len() function​

Get the length of a set:

unique_numbers = {1, 2, 3, 4, 5}
print(len(unique_numbers)) # Output: 5

output

5

Example 6: Length of a bytes using len() function​

Get the length of bytes object:

# byte object
testByte = b'Python'
print('Length of', testByte, 'is', len(testByte)) # Output: 6

testList = [1, 2, 3]
# converting to bytes object
testByte = bytes(testList)
print('Length of', testByte, 'is', len(testByte)) # Output: 3

output

Length of b'Python' is 6
Length of b'\x01\x02\x03' is 3

Example 7: Length of a custom object using len() function​

You have to implement the __len__() method:

class Person:
def __init__(self, height = 180):
self.height = height

def __len__(self):
return self.height

# default length is 180
person1 = Session()
print(len(person1))

# giving custom length
person2 = Person(210)
print(len(person2))

output

180
210