Table of contents
1.
Introduction
2.
What is Python len()?
2.1.
Syntax
2.2.
Parameters
2.3.
Return Value
3.
Using len() for Strings
3.1.
Code in Python
4.
Using len() for Range
4.1.
Code in Python
5.
len() for List and Tuple
5.1.
Code in Python
6.
len() in Dictionary and Set
6.1.
Code in Python
7.
len() for Custom Objects
7.1.
Code in Python
8.
len() for Built-in Data Type
8.1.
Code in Python
9.
Frequently Asked Questions
9.1.
What is the difference between a tuple and a list?
9.2.
Can we calculate the length of the collections using len Python?
9.3.
What is the use of Python len?
9.4.
What is the runtime complexity of the len Python method?
9.5.
Does len() start from 0?
10.
Conclusion
Last Updated: Sep 14, 2024
Easy

Python len() Function

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Python is an interpreted programming language in many fields like Machine Learning, Artificial Intelligence, Data Science, etc. Python provides us with many built-in functions, which are predefined. These functions help to reduce and optimize the code. Today, we will discuss one of these built-in functions.

What is len() Python?

In this article, we will understand the method len(), which is used to find the length of a string as well as a list.

What is Python len()?

Python provides a single method, len(), to calculate the length of a string, list, tuple, and range. This method counts the number of characters in a particular item (which also includes the spaces in a string). 

For example,

“Coding Ninja” contains 12 characters in which 1 is space, 2 are upper-case, and 9 are lower-case letters.

Syntax

For using the len() method. We use the following syntax for applying this method.

len(object)

Parameters

As we see, the syntax of the len() is len(object). So the parameter of the len() is the object, and this object must be a collection or a sequence.

Return Value

This method returns the value of the total number of characters in the particular range, list, tuple, and string.

Using len() for Strings

Let's see an example in which we have to find the length of a string "Coding Ninja is the best platform to learn to code."

Code in Python

str = 'Coding Ninja is the best platform to learn to code.'
print('The length of the String is', len(str))

 

Output

The length of the String is 50

Using len() for Range

This example will calculate the range between 1 to 90 with the help of the len() method.

Code in Python

Range = range(1, 90)
print('The numbers between the given ', Range, ' is', len(Range))

 

Output

The numbers between the given  range(1, 90)  is 89

len() for List and Tuple

Here, we will write a program to count a tuple's length, make a list, and calculate its size.

Code in Python

Tuple = ('C', 'O', 'D', 'I', 'N', 'G')
print('The length of the ', Tuple, ' is', len(Tuple))

List = ['N', 'I', 'N', 'J', 'A', 'S']
print('The length of the ', List, 'is', len(List))

 

Output

The length of the  ('C', 'O', 'D', 'I', 'N', 'G')  is 6
The length of the  ['N', 'I', 'N', 'J', 'A', 'S'] is 6

len() in Dictionary and Set

We will write a program to create a dictionary and set and count the number of elements in the dictionary and set respectively.

Code in Python

#Dictionary
dictionary = {'Name': 'Utkarsh', 'Age': 21, 'Gender': 'Male'};
sampleSet = set()  
    
#Sample Set
sampleSet.add(8) 
sampleSet.add(9) 
sampleSet.add(6)
sampleSet.add(5)
print ("Length of the dictionary: " , len (dictionary))
print("Length of the Set: ", len(sampleSet))

 

Output

Length of the dictionary:  3
Length of the Set:  4

Must read, Swapcase in Python and Convert String to List Python.

len() for Custom Objects

We can define the length of any object we created in any particular class. Let’s take an example to understand the len() for Custom Objects.

Python provides a method in a class to identify the size of an object which will be made. def__len__() is used to define the object's length. Let's see an example of len() in custom objects.

Code in Python

class Student:
  def __init__(self, TotalSub, Sub1, Sub2, Sub3):
    self.TotalSub = TotalSub
    self.Sub1 = Sub1
    self.Sub2 = Sub2
    self.sub3 = Sub3
  def __len__(self):
        return self.TotalSub
S = Student(5, 87, 99, 92)
print('Total Number of Subjects are',len(S))

 

Output

Total Number of Subjects are 5

 

The above code initializes the method in the class and sets the length, and then we get the output using the len() keyword and get the output defined by us in the class.

len() for Built-in Data Type

Let's write a program and use the len function on any of the built-in datatypes, i.e., int, float, and bool.

Code in Python

a = 3
print(len(a))

 

Output

ERROR!
Traceback (most recent call last):
  File "<string>", line 3, in <module>
TypeError: object of type 'int' has no len()

 

The above code uses the len() function for the int data type, and it shows the TypeError, which means that the int data type has no length.

Frequently Asked Questions

What is the difference between a tuple and a list?

Tuples are immutable, while lists are mutable collections of elements. Another difference between tuples and lists is that the former is faster and needs less memory, and the latter is slow and needs more memory.

Can we calculate the length of the collections using len Python?

Yes, we can calculate the length of the collections like a dictionary, set, and frozen set. This method will return the value of the count of the elements present in the dictionary, set, or other collections.

What is the use of Python len?

Python len calculates the list length, tuple, or string. It is also used to count the number of elements in collections like dictionary, set, and frozen set.

What is the runtime complexity of the len Python method?

The Python len used constant time to calculate the sequence and collection lengths. It means the time complexity of the len Python method is O(1) without any dependence on the number of elements in lists.

Does len() start from 0?

No, the len() function in Python does not start from 0. It returns the total number of items in a collection, such as a list, tuple, string, or dictionary. The count begins from 1 for each element, so if a list contains 5 elements, len() will return 5, not 4.

Conclusion

This article taught us about the len Python method, which calculates sequence and collection length. We also discussed some examples of len Python, which shows the code for calculating the length. This article helped us to understand more about the Python language as well as the methods in it.

You can also read about the following articles to learn more.

Enhance your skills in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and more with our Coding Ninjas Studio  Guided Path. If you want to sharpen your coding skills for the test, check out the mock test series and enter the contests on Coding Ninjas Studio! 

Check out The Interview Guide for Product Based Companies and some of the Popular Interview Problems from Top companies like AmazonAdobeGoogleUberMicrosoft, etc., on Coding Ninjas Studio.

Happy Coding!!

Live masterclass