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.
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
my_list = ['John', 32, 32] length = len(my_list) print("The length of list is: ", length)
Technique#02: Using Naive Method (i.e., Python for loop)
my_list = ['John', 32, 32] counter = 0 for i in my_list: counter += 1 print("The length of list is: ", counter)
Technique#03: Using length_hint() Function
from operator import length_hint my_list = ['John', 32, 32] counter = length_hint(my_list) print("The length of list is: ", counter)