Python has different methods to find the total number of elements in a list (or the list length). This article shows three ways to find the list length in Python.
- Python 3 installed.
- A text editor or IDE to write code.
- A way to execute code examples (an IDE or command prompt/terminal).
Finding the Length of a List in Python
Determining the length of a list in Python is a simple task that can be achieved in a variety of ways. Depending on the task at hand, you can use 3 methods to find the length of a list:
- Without functions, using programming logic.
- Using a built-in function (preferred).
- Importing an external function from a library.
The sections below explain all three methods through practical examples.
Method 1: Naïve Counter Method
The first way to determine a list length in Python is to use a
for loop and a counter. This method does not require any built-in or imported functions.
The following code shows how to find the list length using a
for loop and a counter:
my_list = [0,1,2,3,4] counter = 0 for element in my_list: counter += 1 print(counter)
As the loop goes through the elements in the list, the counter increments by one each time. The final value of the counter is the list length.
Method 2: len()
Python offers a built-in method to find the length of a list called
len(). This method is the most straightforward and common way to determine a list length.
To use the
len() function, provide the list as an argument. For example:
my_list = [0,1,2,3,4] print(len(my_list))
len() function returns the element count as an integer.
Note: Methods such as
len() and slicing also work on strings and tuples in Python.
Method 3: length_hint()
operator library contains a method called
length_hint() for estimating the length of iterable objects. The method returns the exact length of lists and objects with a known length. Alternatively, it provides the estimated length.
To use the
length_hint() function, import the method from the
operator library and provide the list as input. For example:
from operator import length_hint my_list = [0,1,2,3,4] print(length_hint(my_list))
The function outputs the Python list length as an integer.
By reading this guide, you now know three different ways to find the length of a Python list. Knowing different methods provides flexibility in choosing the best one for your use case.