Open In App

How To Find the Length of a List in Python

Last Updated : 21 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

List being an integral part of Python programming has to be learned by all Python users and having a knowledge of its utility and operations is essential and always a plus.

Many operations are performed in lists, but in this article, we will discuss the length of a list. The length of a list means the number of elements it has. We are going to look at 8 different methods to find the length of a list in Python.

Example:

Input: lst = [10,20,30,40]
Output: 4
Explanation: The output is 4 because the length of the list is 4.

Find the Length of a List in Python

Below are the methods that we will cover in this article:

1. Find the Length of a List Using len() Function

Python len() function is an inbuilt function in Python. It can be used to find the length of an object by passing the object within the parentheses of the len function.

Python3




# Python len()
li = [10, 20, 30]
n = len(li)
print("The length of list is: ", n)


Output: 

The length of list is: 3

Time Complexity: O(n), where n is the length of the list
Auxiliary Space: O(1)

2. Find the Length of a List Using Naive Method

In this method, one just runs a loop and increases the counter till the last element of the list to know its count. This is the most basic strategy that can be possibly employed in the absence of other present techniques.

Python3




# Initializing list
test_list = [1, 4, 5, 7, 8]
 
# Printing test_list
print("The list is : " + str(test_list))
 
# Finding length of list using loop
# Initializing counter
counter = 0
for i in test_list:
 
    # incrementing counter
    counter = counter + 1
 
# Printing length of list
print("Length of list using naive method is : " + str(counter))


Output: 

The list is : [1, 4, 5, 7, 8]
Length of list using naive method is : 5

Time Complexity: O(n)
Auxiliary Space: O(1)

3. Find the Length of a List Using length_hint() Method

This technique is a lesser-known technique for finding list length. This particular method is defined in the operator class and it can also tell the no. of elements present in the list. Here, we are finding length of list using len() and length_hint() 

Python3




from operator import length_hint
 
# Initializing list
test_list = [1, 4, 5, 7, 8]
 
# Printing test_list
print("The list is : " + str(test_list))
 
# Finding length of list using len()
list_len = len(test_list)
 
# Finding length of list using length_hint()
list_len_hint = length_hint(test_list)
 
# Printing length of list
print("Length of list using len() is : " + str(list_len))
print("Length of list using length_hint() is : " + str(list_len_hint))


Output : 

The list is : [1, 4, 5, 7, 8]
Length of list using len() is : 5
Length of list using length_hint() is : 5

4. Find the Length of a List Using sum() Function

Use iteration inside the sum and with each iteration adds one and at the end of the iteration, we get the total length of the list.

Python3




# Initializing list
test_list = [1, 4, 5, 7, 8]
 
# Printing test_list
print("The list is : " + str(test_list))
 
# Finding length of list
# using sum()
list_len = sum(1 for i in test_list)
 
 
# Printing length of list
print("Length of list using len() is : " + str(list_len))
print("Length of list using length_hint() is : " + str(list_len))


Output:

The list is : [1, 4, 5, 7, 8]
Length of list using len() is : 5
Length of list using length_hint() is : 5

5. Find the Length of a List Using a List Comprehension

Initialize a list called test_list with some values then Initialize a variable called length to 0. Use a list comprehension to generate a sequence of ones for each element in the test_list.

This will create a list of ones with the same length as the test_list. Now use the sum() function to sum all the ones in the list generated by the list comprehension. Assign the sum to the length variable. Print the length variable.

Python3




# Define the list to be used for the demonstration
test_list = [1, 4, 5, 7, 8]
 
# Calculate the length of the list using a list comprehension and the sum function
# The list comprehension generates a sequence of ones for each element in the list
# The sum function then sums all the ones to give the length of the list
length = sum(1 for _ in test_list)
 
# Print the length of the list
print("Length of list using list comprehension is:", length)


Output

Length of list using list comprehension is: 5

Time Complexity: The list comprehension creates a new list with a length equal to the length of the test_list. The sum() function then iterates over this list to compute the sum. Therefore, the time complexity of this algorithm is O(N), where N is the length of the test_list.
Auxiliary Space: The algorithm creates a new list of ones with a length equal to the length of the test_list using the list comprehension. Therefore, the auxiliary space complexity is also O(N), where N is the length of the test_list.

6. Find the Length of a List Using Recursion

We can use a recurcive function that takes a list lst as input and recursively calls itself, passing in a slice of the list that excludes the first element until the list is empty.

The base case is when the list is empty, in which case the function returns 0. Otherwise, it adds 1 to the result of calling the function on the rest of the list.

Python3




# Define a function to count the number of elements in a list using recursion
def count_elements_recursion(lst):
    # Base case: if the list is empty, return 0
    if not lst:
        return 0
    # Recursive case: add 1 to the count of the remaining elements in the list
    return 1 + count_elements_recursion(lst[1:])
 
 
# Test the function with a sample list
lst = [1, 2, 3, 4, 5]
print("The length of the list is:", count_elements_recursion(lst))
 
# Output: The length of the list is: 5


Output

The length of the list is: 5

Time complexity: O(n) where n is the length of the list. This is because the function makes n recursive calls, each taking O(1) time, and there is also O(1) work done at each level outside of the recursive call.
Space complexity: O(n) where n is the length of the list. This is because the function creates n stack frames on the call stack due to the recursive calls.

7. Find the Length of a List Using enumerate() function

Python enumerate() method adds a counter to an iterable and returns it in a form of an enumerating object. 

Python3




# python code to find the length
# of list using enumerate function
list1 = [1, 4, 5, 7, 8]
s = 0
for i, a in enumerate(list1):
    s += 1
print(s)


Output

5

8. Find the Length of a List Using Collections

Alternatively, you can also use the sum() function along with the values() method of the Collections Counter object to get the length of the list.

Python3




from collections import Counter
 
# Initializing list
test_list = [1, 4, 5, 7, 8]
 
# Finding length of list using Counter()
list_len = sum(Counter(test_list).values())
 
print("Length of list using Counter() is:", list_len)
# This code is contributed by Edula Vinay Kumar Reddy


Output

Length of list using Counter() is: 5

Time complexity: O(n), where n is the length of the list. This is because the Counter() function has a time complexity of O(n) when applied to a list of length n, and the values() method and the sum() function both have a time complexity of O(n) when applied to a list of length n.
The space complexity: O(n), as the Counter() function, creates a dictionary with n key-value pairs, each representing an element and its count in the list, respectively. This dictionary takes up O(n) space.

Performance Analysis: Naive vs Python len() vs Python length_hint()

When choosing amongst alternatives it’s always necessary to have a valid reason why to choose one over another. This section does a time analysis of how much time it takes to execute all of them to offer a better choice to use.

Python3




from operator import length_hint
import time
 
# Initializing list
test_list = [1, 4, 5, 7, 8]
 
# Printing test_list
print("The list is : " + str(test_list))
 
# Finding length of list
# using loop
# Initializing counter
start_time_naive = time.time()
counter = 0
for i in test_list:
 
    # incrementing counter
    counter = counter + 1
end_time_naive = str(time.time() - start_time_naive)
 
# Finding length of list
# using len()
start_time_len = time.time()
list_len = len(test_list)
end_time_len = str(time.time() - start_time_len)
 
# Finding length of list
# using length_hint()
start_time_hint = time.time()
list_len_hint = length_hint(test_list)
end_time_hint = str(time.time() - start_time_hint)
 
# Printing Times of each
print("Time taken using naive method is : " + end_time_naive)
print("Time taken using len() is : " + end_time_len)
print("Time taken using length_hint() is : " + end_time_hint)


Output:

The list is : [1, 4, 5, 7, 8]
Time taken using naive method is : 2.6226043701171875e-06
Time taken using len() is : 1.1920928955078125e-06
Time taken using length_hint() is : 1.430511474609375e-06

In the below images, it can be clearly seen that time taken is naive >> length_hint() > len(), but the time taken depends highly on the OS and several of its parameter.

In two consecutive runs, you may get contrasting results, in fact sometimes naive takes the least time out of three. All the possible 6 permutations are possible.

  naive > len() > length_hint()

naive > len()=length_hint() 

naive > length_hint() >len() 

naive > length_hint()  > len()

We have discussed 8 different methods to find the length of a list in Python. We have also done a performance analysis to check which method is the best.

You can use any of the above methods to find the length of a list. Finding list length is very useful when dealing with huge lists and you want to check the number of entries.

Check Out More Python Lists Pages:



Previous Article
Next Article

Similar Reads

Python | Find maximum length sub-list in a nested list
Given a list of lists, write a Python program to find the list with maximum length. The output should be in the form (list, list_length). Examples: Input : [['A'], ['A', 'B'], ['A', 'B', 'C']] Output : (['A', 'B', 'C'], 3) Input : [[1, 2, 3, 9, 4], [5], [3, 8], [2]] Output : ([1, 2, 3, 9, 4], 5) Let's discuss different approaches to solve this prob
3 min read
Python string length | len() function to find string length
The string len() function returns the length of the string. In this article, we will see how to find the length of a string using the string len() method. Example: C/C++ Code string = "Geeksforgeeks" print(len(string)) Output13String len() Syntax len(string) Parameter String: string of which you want to find the length. Return: It returns
3 min read
Python | Convert 1D list to 2D list of variable length
Given a 1D list 'lst' and list of variable lengths 'var_lst', write a Python program to convert the given 1D list to 2D list of given variable lengths. Examples: Input : lst = [1, 2, 3, 4, 5, 6] var_lst = [1, 2, 3] Output : [[1], [2, 3], [4, 5, 6]] Input : lst = ['a', 'b', 'c', 'd', 'e'] var_lst = [3, 2] Output : [['a', 'b', 'c'], ['d', 'e']] Metho
7 min read
How to Fix: Length of values does not match length of index
In this article we will fix the error: The length of values does not match the length of the index in Python. Cases of this error occurrence: C/C++ Code # importing pandas import pandas as pd sepal_length = [5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9] sepal_width = [4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9, 5.1, 5.2, 5.3] petal_length = [3.3, 4.6, 4
2 min read
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
Python | Convert list of tuples to list of list
This is a quite simple problem but can have a good amount of application due to certain constraints of Python language. Because tuples are immutable, they are not easy to process whereas lists are always a better option while processing. Let's discuss certain ways in which we can convert a list of tuples to list of list. Method #1: Using list compr
8 min read
Python | Convert List of String List to String List
Sometimes while working in Python, we can have problems of the interconversion of data. This article talks about the conversion of list of List Strings to joined string list. Let's discuss certain ways in which this task can be performed. Method #1 : Using map() + generator expression + join() + isdigit() This task can be performed using a combinat
6 min read
Python | Sort a List according to the Length of the Elements
In this program, we need to accept a list and sort it based on the length of the elements present within. Examples: Input : list = ["rohan", "amy", "sapna", "muhammad", "aakash", "raunak", "chinmoy"] Output : ['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad'] Input : list = [["ram", "mohan", "aman"], ["gaurav"], ["amy", "sima", "a
4 min read
Python | Average of each n-length consecutive segment in a list
Given a list, the task is to find the average of each n-length consecutive segment where each segment contains n elements. Example: Input : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] Output: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] Explanation: Segment 1 - [1, 2, 3, 4, 5] => 15/5 = 3 Segment 2 - [2,
3 min read
Python | Sort list of lists by lexicographic value and then length
There are many times different types of sorting has been discussed in python lists. The sorting of python list of lists has also been discussed. But sometimes, we have two parameters upon which we need to sort. First one being the list sum and next being its length. Let's discuss how this type of problem can be solved. Method #1 : Using sort() twic
6 min read
Practice Tags :