Tutorial Study Image

Python len()

The built-in function len() is used to return the length of the object that is a number of elements in the object. Here the object may be a string, array, list, tuple, dictionary, etc.


len(object) # object can be string,sets,tuples,dictionary etc

len() Parameters:

Takes only one parameter. In this the sequence can be string, bytes, tuple, list, or range and collection can be a dictionary, set, or frozen set.

Parameter Description Required / Optional
object a sequence or a collection Required

len() Return Value

If an argument is missing or passing an invalid argument it will raise a TypeError exception.

Input Return Value
 an object  length of the object(integer value)

Examples of len() method in Python

Example 1: How len() works with tuples, lists and range?


testList = []
print(testList, 'length is', len(testList))

testList = [1, 2, 3]
print(testList, 'length is', len(testList))

testTuple = (1, 2, 3)
print(testTuple, 'length is', len(testTuple))

testRange = range(1, 10)
print('Length of', testRange, 'is', len(testRange))
 

Output:

[] length is 0
[1, 2, 3] length is 3
(1, 2, 3) length is 3
Length of range(1, 10) is 9

Example 2: How len() works with strings and bytes?


testString = ''
print('Length of', testString, 'is', len(testString))

testString = 'Python'
print('Length of', testString, 'is', len(testString))

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

testList = [1, 2, 3]

# converting to bytes object
testByte = bytes(testList)
print('Length of', testByte, 'is', len(testByte))
 

Output:

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

Example 3: How len() works with dictionaries and sets?


testSet = {1, 2, 3}
print(testSet, 'length is', len(testSet))

# Empty Set
testSet = set()
print(testSet, 'length is', len(testSet))

testDict = {1: 'one', 2: 'two'}
print(testDict, 'length is', len(testDict))

testDict = {}
print(testDict, 'length is', len(testDict))

testSet = {1, 2}
# frozenSet
frozenTestSet = frozenset(testSet)
print(frozenTestSet, 'length is', len(frozenTestSet))
 

Output:

{1, 2, 3} length is 3
set() length is 0
{1: 'one', 2: 'two'} length is 2
{} length is 0
frozenset({1, 2}) length is 2

Example 4: How len() works for custom objects?


class Session:
    def __init__(self, number = 0):
      self.number = number
    
    def __len__(self):
      return self.number


# default length is 0
s1 = Session()
print(len(s1))

# giving custom length
s2 = Session(6)
print(len(s2))
 

Output:

0
6