Python Program To Find Length Of A List
The length of a list is equal to the number of elements present in it.
Find the length of a List using the Naive method in Python
This is the most basic approach to finding the length of a list. Here, we maintain a counter variable and initialize it 0.
We then count the number of elements in the list using a for loop. In each iteration, we increment the value of the counter variable by 1. When the loop terminates the counter variable stores the length of the list.
Let's look at the algorithm of this approach to understand better.
Algorithm to find the length of the list in Python
Initialize a list je_list
Declare a counter variable je_counter and initialize it to 0
Start for-each loop to je_list and increment je_counter variable by 1
Display length using je_counter
# Initialise a list je_list = [ 1, 3, 43, 66, 321, 4 ] # declare and initialize a counter variable je_counter = 0 # apply a for each loop for je_ele in je_list: je_counter = je_counter +1 # display je_counter print(je_counter)
Find the length of a List using len() method in Python
Python has an in-built method called the len() method. This method takes an iterable object as its argument and returns the length of that iterable object.
It is the most convenient and commonly used approach. Look at the code below:
# Initialise a list je_list = [ 1, 3, 43, 66, 321, 4 ] # using length function je_len = len(je_list) # print length print(je_len)
Find the length of a List using the length_hint() method in Python
This method is exactly like the len() method except that declared in the operator class. So, we must import the operator class before using this method. It returns the number of elements present in a list. Look at the code below.
from operator import length_hint # Initialise a list je_list = [ 1, 3, 43, 66, 321, 4 ] # using length_hint function je_len = length_hint(je_list) # print length print(je_len)