The length of a list is equal to the number of elements present in the list.
This is the most basic approach to finding the length of a list. Here, we maintain a counter variable and initialize it as 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 it better.
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)
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)
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)