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.
len(obj)
obj
: The object passed can be a sequence such as a string, tuple, list, etc., or a collection, such as a dictionary, set, etc.The function returns the length of the object as an integer.
# Calling len() on sequences:# stringstringTest = "educative"lenOfStr = len(stringTest)print("length of string:" , lenOfStr)# tupletupleTest = (545, 643, 746, 346, 467)lenOfTuple = len(tupleTest)print("length of tuple:" , lenOfTuple)# listlistTest = ["hello", 6, "765"]lenOfList = len(listTest)print("length of list:" , lenOfList)# Calling len() on collections:# dictionarydictionaryTest = {1 : "python", 2 : "C++", 3 : "Java", 4 : "HTML"}lenOfDictionary = len(dictionaryTest)print("length of dictionary:" , lenOfDictionary)# setsetTest = set() # empty setlenOfSet = len(setTest)print("length of set:" , lenOfSet)