Table of contents
1.
Introduction
2.
A Brief about Lists in Python
3.
How are lists used in Python?
4.
Approaches to Calculate the Length of a List in Python
4.1.
Using Recursion
4.2.
Python
4.3.
Using Built-in Function len()
4.4.
Python
4.5.
Using a Loop
4.6.
Python
4.7.
Using __len__() Method
4.8.
Python
4.9.
Using a List Comprehension with the sum() Function
4.10.
Python
4.11.
Using Collections Module
4.12.
Python
4.13.
Using enumerate() Method
4.14.
Python
5.
Comparison Between Various Length Functions in Python
5.1.
Code In Python
5.2.
Python
5.2.1.
Output
6.
Frequently Asked Questions
6.1.
What is a list in Python?
6.2.
What is the length of a list in Python?
6.3.
What is the limit length of a list in Python?
6.4.
How do you find the length of a list in Python?
6.5.
Are there other ways to find the length of a list in Python other than the len() function?
7.
Conclusion 
Last Updated: Nov 6, 2024
Easy

How to Find the Length of a List in Python?

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this blog, we will discuss how to find Python list length. We will understand the ways to find the length of a list in Python. We will also see some examples of it. Before diving deep into the topic of Python list length, let us understand what a list is.

list length in python

Also see, Merge Sort Python

A Brief about Lists in Python

list in Python is a built-in data structure. It is used to store a collection of items. It is a mutable and ordered sequence of elements. These elements can be of any type, such as numbers, strings, and even other lists. A list is denoted by square brackets []. The elements are separated by commas in a list. 

Let us understand a list with the help of an example:

ninjas_list = ['ninja1','ninja2','ninja3','ninja4']

 

In this example, ninjas_list is a list that contains the string from ‘ninja1’ to ‘ninja4’. You can access the elements of a list by their index. The index starts at 0 for the first element. You can access the first element of ninjas_list by using ninjas_list[0], which will return ‘ninja1’. You can also modify the elements of a list by using the index notation like this:

ninjas_list[2] = ‘hello ninjas’

 

This will change the third element of ninjas_list from ‘ninja3’ to ‘hello ninja’. Lists also support a wide range of built-in methods and functions that you can use to manipulate and process their elements.

Now you might be thinking about how to find the length of ninjas_list. Let us move to our main topic.

How are lists used in Python?

In Python, lists are versatile, ordered collections of items that allow you to store and manipulate a sequence of values in a single variable. Lists can contain elements of any data type, including integers, floats, strings, or even other lists, making them highly flexible for organizing data.

Approaches to Calculate the Length of a List in Python

There are various ways to find the length of a list in Python. 

Let us understand each one of them one by one.

Using Recursion

o calculate the length of a list in Python using recursion, we can create a recursive function that counts each element by reducing the list size until it becomes empty. This approach allows us to calculate the length without using the built-in len() function.

Approach

  1. Define a recursive function that takes a list as input.
  2. If the list is empty (base case), return 0.
  3. If the list is not empty, return 1 plus the result of calling the function with the list sliced from the second element onward (i.e., list[1:]).
  4. Each recursive call reduces the list by one element until it’s empty, counting each element along the way.

Code

  • Python

Python

def recursive_length(lst):
# Base case: empty list
if lst == []:
return 0
# Recursive case
else:
return 1 + recursive_length(lst[1:])

# Example list
example_list = [10, 20, 30, 40, 50]

# Calculate length
length = recursive_length(example_list)
print("Length of the list:", length)
You can also try this code with Online Python Compiler
Run Code

Output

Length of the list: 5

Explanation

  • For each recursive call, the function checks if the list is empty:
    • If it is, it returns 0.
    • If it is not, it returns 1 + recursive_length(lst[1:]).
  • lst[1:] creates a new list starting from the second element, which effectively reduces the list by one item for the next recursive call.

Using Built-in Function len()

You can use the built-in len() function in Python to find the length of a list. Here is an example:

Code in Python  

  • Python

Python

ninjas_list = ['ninja1','ninja2','ninja3','ninja4']
print(len(ninjas_list))
You can also try this code with Online Python Compiler
Run Code

Output

4

 

In this example, we have a list named ninjas_list containing 4 elements. We pass this list as an argument to the len() built-in function. This will return the number of elements in the list, i.e., 4.

Note: The len() function works not only on lists but on other sequence types such as strings, tuples, and ranges as well.

Using a Loop

You can use a loop to find the Python list length. Here is an example:

Code in Python

  • Python

Python

ninjas_list = ['ninja1','ninja2','ninja3','ninja4']
ans = 0
for element in ninjas_list:
   ans += 1
print(ans)
You can also try this code with Online Python Compiler
Run Code

Output

4

 

In this example, we have used a loop, and we are increasing the count while traversing the loop.

Using __len__() Method

You can use a __len__() function to find the Python list length. Here is an example:

Code in Python

  • Python

Python

ninjas_list = ['ninja1','ninja2','ninja3','ninja4']
lengthOfList = ninjas_list.__len__()
print(lengthOfList)
You can also try this code with Online Python Compiler
Run Code

Output

4

 

In this example, we have used the __len__() function to find the Python list length. It is a special method in Python. It returns the length of an object. It is called by the built-in len() function when we pass an object as an argument to it. 

Using a List Comprehension with the sum() Function

You can use list comprehension with the sum() method to find the Python list length. Here is an example:

Code in Python

  • Python

Python

ninjas_list = ['ninja1','ninja2','ninja3','ninja4']
lengthOfList = sum(1 for _ in ninjas_list)
print(lengthOfList)
You can also try this code with Online Python Compiler
Run Code

Output

4

 

In this example, we have used the sum() method to find the length of the list. List comprehension with the sum() function is a concise way to calculate the sum of elements in a list in Python.

Using Collections Module

You can use the collections module’s class Counter to find the Python list length. Here is an example:

Code in Python

  • Python

Python

from collections import Counter

ninjas_list = ['ninja1','ninja2','ninja3','ninja4']
takingCount = Counter(ninjas_list)
lengthOfList = sum(takingCount.values())
print(lengthOfList)
You can also try this code with Online Python Compiler
Run Code

Output

4

 

In this example, we have used Counter class. The collections module provides a Counter class. This can be used to count the number of occurrences of each element in a list. We can use the Counter class to find the length of a list by passing the list as an argument to the Counter() constructor and then getting the sum of the values in the resulting dictionary.

Using enumerate() Method

You can use the enumerate() method to find the Python list length. Here is an example:

Code in Python

  • Python

Python

ninjas_list = ['ninja1','ninja2','ninja3','ninja4']
ans = 0
for index, value in enumerate(ninjas_list):
   ans += 1
print(ans)
You can also try this code with Online Python Compiler
Run Code

Output

4

 

In this example, we have used enumerate() method. It is a built-in function in Python. It can be used to iterate over a list. It returns both the index and value of each element in the list. While enumerate() is not typically used to find the length of a list, it can be used to count the number of iterations and hence the length of the list.

Now you might have a doubt about which method you need to use to find the Python list length. Let us understand this.

Comparison Between Various Length Functions in Python

Most of us are always confused about choosing the method to find the Python list length. Let us understand this with the help of an example. 

Code In Python

  • Python

Python

import timeit
import time
from collections import Counter

ninjas_list = ['ninja1','ninja2','ninja3','ninja4']

# Using built-in len() function
print("Using len():")
print(timeit.timeit(lambda: len(ninjas_list)))

#Using a loop
print("Using loop:")
start_time=time.time()
count=0
for i in ninjas_list:
   count=count+1
end_time=str(time.time()-start_time)
print(end_time)

# Using list comprehension with sum() function
print("Using list comprehension and sum():")
print(timeit.timeit(lambda: sum(1 for _ in ninjas_list)))

# Using Counter from collections module
print("Using Counter:")
print(timeit.timeit(lambda: sum(Counter(ninjas_list).values())))

# Using enumerate()
print("Using enumerate():")
print(timeit.timeit(lambda: sum(1 for _ in enumerate(ninjas_list))))
You can also try this code with Online Python Compiler
Run Code

Output

Using len():
0.20884473201294895
Using loop:
5.9604644775390625e-06
Using list comprehension and sum():
1.0116307890129974
Using Counter:
1.6803069720044732
Using enumerate():
0.6431273189955391

 

In this example, we have used timeit module to compare the time taken by different methods to find the Python list length. This provides a simple way to time small bits of Python code.

We first create a list ninjas_list which contains 4 elements. We then time the execution of each method to find the length of the list using timeit module. 

The lambda functions inside timeit.timeit() is used to wrap each method call so that timeit can time the execution of the method without actually calling it multiple times.

Note: The actual execution times will depend on the size of the list and the specific hardware and software environment on which the code is running. The above example should give a rough idea of the relative performance of each method.

So the built-in method len() takes less time to find the length of the list in Python.

You can also practice with the help of Online Python Compiler

Must Read Python List Operations

Frequently Asked Questions

What is a list in Python?

A list is a collection of elements in Python, which can be of any type. It is one of the most commonly used data structures in Python. It is defined by enclosing a comma-separated sequence of elements inside square brackets [].

What is the length of a list in Python?

The length of a Python list is the total number of items it contains, accessible using the len() function.

What is the limit length of a list in Python?

The limit length of a list in Python depends on available memory, typically reaching several million elements on modern systems.

How do you find the length of a list in Python?

You can find the length of a list in Python using the len() function. For example, to find the length of a list my_list, you can do len(my_list).

Are there other ways to find the length of a list in Python other than the len() function?

Yes, there are other ways to find the length of a list in Python. For example, you can use the collections module to create a Counter object and then access the len() attribute to find the length of the list. You can also use the enumerate() function to iterate over the elements of the list and count the number of iterations.

Conclusion 

In this article, we have discussed Python list length. We have covered different ways to find the length of the list. We understood which method we could use to find the Python list length. You can check our other blogs to explore more in Python:

We hope this blog helped you to understand Python list length. You can refer to our guided paths on the Code360 Studio platform. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

You can also consider our paid courses such as DSA in Python to give your career an edge over others! 

Live masterclass