In this blog post, we’ll discuss how to find the length of the list in Python.
What is a Python list?
Python list is a mutable, ordered sequence of elements. List elements can be of any type, from numbers and strings to more complex types such as objects and tuples. Python list is used as a sequence that can be managed through various built-in methods.
The most commonly used method to find the Python list length is by using the built-in len()
method. The returned result represents the number of total elements in the list.
We’ll go into more detail in the following sections.
Find the Python list length using the len()
method
The len()
method calculates how many elements the given sequence or collection contains. It relies on a __len__()
method defined by the list itself. Since it yields results in O(1) time, it is also the optimal method for calculating the Python list size.
The syntax looks like this:len(X)
X is the Python list defined with list()
or with square brackets []
.
Let’s go through a few examples to see it in action.
list_example = [10, 20, 30, 'abc', 40] len(list_example) # 5 list_example = [] list_example.append('a') list_example.append('b') list_example.append('c') len(list_example) # 3 list_example = list() list_example.append('a') list_example.append('b') len(list_example) # 2 list_example = [] len(list_example) # 0
Find the Python list size using the naive approach
To find the number of elements list contains, you can also count list items manually using the for loop. This simple approach is not as effective as using Python’s len()
method since it requires O(n) time. Still, it can be used when performance is not an important factor.
Pseudocode for counting list elements goes like this:
- Initialize the
counter
variable with zero - Iterate over elements in a list using the for loop
- For each iteration, increase the
counter
value by 1
- For each iteration, increase the
- After traversing the list elements is over, the
counter
value represents the total number of elements in a Python list
Let’s see it in code now.
list_example = [10, 20, 30, "abc", 40] counter = 0 for val in list_example: counter += 1 print(counter) # 5
Bonus – Performance comparison between the len()
method and naive approach
To demonstrate why it is better to use the len()
method for calculating Python list length, I’ll show you the comparison between both approaches we discussed.
Let’s first import the timeit
module that we’ll use for time analysis. We also initialize the Python list with random values.
import timeit a = [10, 20, 30, 'abc', 40]
The experiment is performed by using the timeit
Python module that allows you to calculate the execution time of a particular expression. In our experiment we have two methods we want to test:
len_approach()
– uses thelen()
method to find Python list size.forloop_approach()
– uses the for loop to traverse the list and calculate the total number of elements.
To see the difference more clearly, we’ll evaluate each method 10000 times and then the average execution time will be calculated.
Let’s run the test for the len()
method approach.
def len_approach(x): return len(x) loop = 10000 result_len = timeit.timeit('len_approach(a)', globals=globals(), number=loop) print(result_len / loop) # 4.4359e-07
Now let’s see the results for the for-loop approach.
def forloop_approach(x): counter = 0 for val in x: counter += 1 return counter loop = 10000 result_forloop = timeit.timeit('forloop_approach(a)', globals=globals(), number=loop) print(result_forloop / loop) # 1.1368e-06
As you can see, using the len()
method was significantly faster than manually calculating the list size. When averaged over 10000 executions, the len()
method took 0.00044 milliseconds per execution, while for-loop approach took 0.00114 milliseconds per execution.
Approach | Average execution time (ms) |
len() method | 0.00044 |
For loop | 0.00114 |