How to use the len() method in Python

The len() function is a built-in Python function that returns the length of any object passed to it. It calls the object’s length function (__len__()) to calculate the length.

Syntax

len(obj)
The function call len("string") will return 6, the length of the word 'string'

Parameter

  1. obj: The object passed can be a sequence such as a string, tuple, list, etc., or a collection, such as a dictionary, set, etc.

Return value

The function returns the length of the object as an integer.

Example code

# Calling len() on sequences:
# string
stringTest = "educative"
lenOfStr = len(stringTest)
print("length of string:" , lenOfStr)
# tuple
tupleTest = (545, 643, 746, 346, 467)
lenOfTuple = len(tupleTest)
print("length of tuple:" , lenOfTuple)
# list
listTest = ["hello", 6, "765"]
lenOfList = len(listTest)
print("length of list:" , lenOfList)
# Calling len() on collections:
# dictionary
dictionaryTest = {1 : "python", 2 : "C++", 3 : "Java", 4 : "HTML"}
lenOfDictionary = len(dictionaryTest)
print("length of dictionary:" , lenOfDictionary)
# set
setTest = set() # empty set
lenOfSet = len(setTest)
print("length of set:" , lenOfSet)

Free Resources