Get Length of the List in Python

  1. Get Length of the List in Python Using the len() Function
  2. Get the Length of the List in Python Using the length_hint() Method of the operator Module

This tutorial will explain how to get the length of the list in Python. We will look into multiple methods to get the length of the list. A list is a standard data type in Python which is used to store multiple values in it. A list is an ordered, mutable and iterable object, allowing duplicate elements, unlike a set in Python.

The different methods to get the length of a list in Python are explained below.

Get Length of the List in Python Using the len() Function

The len() Function in Python takes an iterable object as input and returns the number of elements in it. To get the length of the list, we can pass the list to the len() function. The example code below demonstrates how to use the len() function to get the length of Python’s list.

mylist = [2,453,567,123,434]
print(len(mylist))

Output:

5

One thing that should be kept in mind that the len() function does not return the number of elements in the list. As in the case of a 2D list, it will still treat the list as a 1D list and only return its length. The example code below demonstrates the result of the len() function with a 2D list as the input.

mylist = [[1,2,3],[4,5]]
print(len(mylist))

Output:

2

Get the Length of the List in Python Using the length_hint() Method of the operator Module

In Python 3.4 and above, we can also use the length_hint() method of the operator module. The length_hint() method takes an iterable object as input and returns the object’s length as output. It is similar in working as the len() method, but the advantage of this method is that it can handle more data types than the len() method i.e. the list_iterator type of Python. The len() function is more reliable than the length_hint() method, as it does not always return the exact length of the input.

The example code below demonstrates how to use the length_hint() method to get the length of the list in Python.

from operator import length_hint

mylist = [[1,2,3],[4,5]]
print(length_hint(mylist))

myiter = iter([[1,2,3],[4,5]])
print(length_hint(myiter))

Output:

2
2
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python List

  • Find Maximum Value in a List in Python
  • Convert Set to List in Python