A python list is a collection of elements.

Length of a list in python is the total number of elements in it.
Length is also referred as the size of list.

This article will explain 3 ways in which python list length can be checked.

Method 1: Using len() function
Python’s inbuilt len() function accepts an object as arguments and returns the number of items in it or the length or size of the object.

Python docs for len() state

Return the number of items in a container.

Example program that uses len() to get the size of list follows.

list_numbers = [1,3,5,6,7,9]
length = len(list_numbers)
print("Length of list is :", length)

which prints

Length of list is : 6

Method 2: Using for loop
This is a traditional method of calculating the length of a list and should be used when you are asked to get the list length without using len() function or any other built in python method.

This method iterates over the list and in every iteration increments a variable by 1. This variable is initialized to 0 before the start of iteration.
At the end of loop, the value of this element will be equal to the number of iterations or the number of elements in the list.

list_numbers = [1,3,5,6,7,9]
# initialize variable to 0
length = 0
# iterate list
for i in list_numbers:
   # increment variable
   length += 1
print("Length of list is :", length)

A python list can be iterated in many ways but here we are using a for loop.
Output of this example is

Length of list is : 6

This is not a recommended method since it requires iterating the complete list. For larger list, it may be quite slow.

Method 3: Using operator module
Python’s operator module contains a function length_hint which accepts an object argument and returns the count of its elements.

from operator import length_hint

list_numbers = [1,3,5,6,7,9]
length = length_hint(list_numbers)
print("Length of list is :", length)

Before using length_hint function, you need to import the module and function itself as shown above. The example prints

Length of list is : 6

Out of all the three methods to get the length of list, len() function is the fastest and you should use this only, if not asked otherwise.

Do not forget to Hit the clap if the article was useful.

Liked the article ? Spread the word...

Leave a Reply