len() in python

How to find the length of a String in python

len() method in python returns the total number of elements in an object. It also returns the number of characters in a string or we can say the length of a string. It is an inbuilt method in python. The function gives the length of any tuple, list, range, dictionary etc in python. It takes a data type string as a parameter and tends to return an integer value which is the total number of characters present in the string. The return type could also be an array of collections or a list etc.

If the user passes an invalid statement or the return type fails to pass an argument, the code throws a TyperError exception.   

Syntax of len() function:


Python program to understand the use of the function:

array = ['A','B','T','R']

print('The length of the Array is')

x = len(array)


The output of the python code will be:

The length of the Array is

How len() works with tuples in python:

Tuple = (10, 20, 30)
print('length of tuple is', len(Tuple))

The output of python len() program using tuples will be:

('length of the tuple is', 3)

How len() works with lists in python:

List = [10, 20, 30]
print('length pf the list is', len(List))

The output of python len() program using lists will be:

('length pf the list is', 3)

How len() works with Ranges:

Range = range(1, 15)
print('Length of the range is', len(Range))

The output of len() program using ranges will be:

('Length of the range is', 14)

If a user does not wish to use an inbuilt function for calculating the length of the string, there is an alternative method. It is done by using for loop in python. It can be performed by incrementing the value with every step.

Difference between __len__ and len()

As we discussed, len() in python is used to get the length of a string i.e the characters present in it. Its return type could be an array or a list. However, __len__is a function internally calls in an object in python. Its return type can never be an array.

Leave a comment

Your email address will not be published. Required fields are marked *

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Python Online Quiz

Level up your coding skills with our interactive programming quiz!