BlogsDope image BlogsDope

Python len() function

March 16, 2021 PYTHON FUNCTION 2899

One of the most common tasks performed during programming is finding the length of a certain object and Python provides a very powerful function called as the len() function that can help you to determine the length (the number of items) of a particular object whether it is a string, list, tuple, etc.

Python len() Syntax

The following is the syntax of the len() method:


Python len() Parameters

The len() function takes only a single parameter:

  • s - This parameter refers to the object whose length we want to find and it can be a sequence such as a string, bytes, tuple, list, etc., or a collection such as a dictionary, set, etc.

Python len() Return Value

The len() function returns the length of the passed parameter, i.e. the number of elements of the object. A TypeError is raised by the len() function if we fail to pass a parameter or pass an invalid parameter.

Python len() Examples

Example 1: With sequences like string, tuple, list, etc.

# with list
lst = [1, 2, 3]
print("Length of list is",len(lst))

# with tuple
tup = (1, 2, 3, 4)
print("Length of tuple is",len(tup))

# with range
r = range(0,5)
print("Length of range is",len(r))

# with string
st = 'Coding'
print("Length of String is",len(st))


​Length of list is 3
Length of tuple is 4
Length of range is 5
Length of String is 6

Example 2: With collections like dictionary, set, frozen set, etc.

# with dictionary
d1 = {}
print("Length of dictionary is",len(d1))
d2 = { 'a': 1, 'b': 2}
print("Length of dictionary is",len(d2))

# with set
s1 = set()
print("Length of set is",len(s1))
s2 = {1, 2, 3}
print("Length of set is",len(s2))

# with frozen set
fs = frozenset(s2)
print("Length of frozen set is",len(fs))


​Length of dictionary is 0
Length of dictionary is 2
Length of set is 0
Length of set is 3
Length of frozen set is 3

Example 3: Exceptions thrown by len() function.

# empty len() function

# invalid object passed
import math


​TypeError: len() takes exactly one argument (0 given)
TypeError: object of type 'module' has no len()

In this way we have seen the working of the Python len() function and how it can be used to find the length of various objects in Python.

Liked the post?
Zealous Learner.
Editor's Picks

Please login to view or add comment(s).