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:
| Parameter | Condition | Description |
|---|---|---|
object |
Required | The 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.
Examples
Example 1: Length of a String using len() function
Get the length of a string:
name = "Tutorial Reference"
print(len(name)) # Output: 18output
18Example 2: Length of a List using len() function
Get the length of a list:
langs = ["Python", "JavaScript", "Rust"]
print(len(langs)) # Output: 3output
3Example 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: 3output
3Example 4: Length of a Tuple using len() function
Get the length of a tuple:
coordinates = (40.689167,-74.044444)
print(len(coordinates)) # Output: 2output
2Example 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: 5output
5Example 6: Length of a bytes using len() function
Get the length of bytes object:
testByte = b'Python'
print('Length of', testByte, 'is', len(testByte)) # Output: 6
testList = [1, 2, 3]
testByte = bytes(testList)
print('Length of', testByte, 'is', len(testByte)) # Output: 3output
Length of b'Python' is 6
Length of b'\x01\x02\x03' is 3Example 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
person1 = Session()
print(len(person1))
person2 = Person(210)
print(len(person2))output
180
210