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 Algorithms, Competitive Programming, JavaScript, System 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 Amazon, Adobe, Google, Uber, Microsoft, etc., on Coding Ninjas Studio.
Happy Coding!!