List in Python is a collection datatype capable of storing different types of data items. The sequence of data items in a Python list is ordered, changeable, and can be duplicated. There are other collection data types too, which allows storing data of various types such as tuple, dictionary, etc. However, list is most commonly used, as it provides O(1) time complexity to calculate the list size.
The items in a list are enclosed in square brackets [] and are comma-separated (,).
In this article, we will discuss three techniques of calculating list size in Python, which are:
- Using the len() method.
- Using Naive Method (i.e., Python for-loop).
- Using length_hint() function.
Table of Contents
Technique#01: Using the Python len() Method
len() is a built-in function of Python, and it is the most commonly used approach by programmers to find out the length of an iterable. It can be used not only on the list but also with the array, tuple, dictionary, etc.
It accepts one argument only, which is iterable whose length you want to find, that is, list in our case and, it will simply return the length (i.e., number of items) in that list.
Let’s go through a coding-based example of this approach.
Code
my_list = ['John', 32, 32]
length = len(my_list)
print("The length of list is: ", length)
Output

Technique#02: Using Naive Method (i.e., Python for loop)
In the Naive method, a traditional for loop is used to iterate over the list of items, and a counter variable is defined to count the number of elements in list. Initially, the counter variable is given the value zero, and each time the for loop encounters an item in list, the counter variable gets incremented by one. In the end, the variable will hold a value equals to the number of items in the list. Let’s see an example below:
Code
my_list = ['John', 32, 32]
counter = 0
for i in my_list:
counter += 1
print("The length of list is: ", counter)
Output

Technique#03: Using length_hint() Function
Python has a inbuilt function of length_hint() in the operator module to calculate the number of elements in list. The usage is illustrated below:
Code
from operator import length_hint
my_list = ['John', 32, 32]
counter = length_hint(my_list)
print("The length of list is: ", counter)
Output

Conclusion
In this article, we understood three ways to calculate the length of a list in Python. All those methods were illustrated with the implementation of short code snippets. However, the most commonly used and recommended way to calculate the length of the list is the use of the len() method.