The Wayback Machine - https://web.archive.org/web/20240930235158/https://www.geeksforgeeks.org/python-ways-to-find-length-of-list/
Open In App

How To Find the Length of a List in Python

Last Updated : 26 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The length of a list means the number of elements it has. The 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. Below is a simple Python program to find length of a list using len()

Python
l1 = [10, 20, 30]
n = len(l1)
print("Length of l1 : ", n)

l2 = []
n = len(l2)
print("Length of l2 : ", n)

l3 = [[10, 20], ["gfg", "courses"], 10.5]
n = len(l3)
print("Length of l3: ", n)

Output
Length of l1 :  3
Length of l2 :  0
Length of l3:  3

We are now going to look at 7 other different methods to find the length of a list in Python.

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.

Python
# 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

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.

Python
# 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.

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.

Python
# 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

Find the Length of a List Using Recursion

We can use a Recursion 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.

Python
# 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

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. 

Python
# 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

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.

Python
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

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() 

Python
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

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.

Python
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 : 1.1920928955078125e-06
Time taken using len() is : 9.5367431640625e-07
Time taken using length_hint() is : 9.5367431640625e-07

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.

Image

naive > len() > length_hint()

Image

naive > len()=length_hint() 

Image

naive > length_hint() >len() 

Image

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.



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: [GFGTABS] Python string = "Geeksforgeeks" print(len(string)) [/GFGTABS]Output13String len() Syntaxlen(string) ParameterString: string of which you want to find the length. Retu
5 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
Python Program For Finding The Length Of Longest Palindrome List In A Linked List Using O(1) Extra Space
Given a linked list, find the length of the longest palindrome list that exists in that linked list. Examples: Input : List = 2->3->7->3->2->12->24 Output : 5 The longest palindrome list is 2->3->7->3->2 Input : List = 12->4->4->3->14 Output : 2 The longest palindrome list is 4->4 Recommended: Please sol
3 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
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 | 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
Python | Zipping two unequal length list in dictionary
Given two lists of possibly unequal lengths, the task is to zip two lists in a dictionary such that the list with shorter length will repeat itself. Since the dictionary in Python is an unordered collection of key:value pairs, the result will be printed on unordered fashion. Method #1: Using itertools() C/C++ Code # Python code to demonstrate # ret
4 min read
Python | Split list of strings into sublists based on length
Given a list of strings, write a Python program to split the list into sublists based on string length. Examples: Input : ['The', 'art', 'of', 'programming'] Output : [['of'], ['The', 'art'], ['programming']] Input : ['Welcome', 'to', 'geeksforgeeks'] Output : [['to'], ['Welcome'], ['geeksforgeeks']] Approach #1 : Naive A naive approach for the abo
3 min read
Python | Sort dictionary by value list length
While working with Python, one might come to a problem in which one needs to perform a sort on dictionary list value length. This can be typically in case of scoring or any type of count algorithm. Let's discuss a method by which this task can be performed. Method 1: Using sorted() + join() + lambda The combination of above functions can be used to
4 min read
Python - Sum of different length Lists of list
Getting the sum of list is quite common problem and has been dealt with and discussed many times, but sometimes, we require to better it and total sum, i.e. including those of nested list as well. Let’s try and get the total sum and solve this particular problem. Method #1 : Using list comprehension + sum() We can solve this problem using the list
5 min read
Python | Extract length of longest string in list
Sometimes, while working with a lot of data, we can have a problem in which we need to extract the maximum length of all the strings in list. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using max() + generator expression, The combination of above functionalit
4 min read
Python - Length of shortest string in string list
Sometimes, while working with a lot of data, we can have a problem in which we need to extract the minimum length string of all the strings in list. This kind of problem can have applications in many domains. Let’s discuss certain ways in which this task can be performed. Method #1 : Using min() + generator expression The combination of the above f
5 min read
Python - Maximum column values in mixed length 2D List
The usual list of list, unlike conventional C type Matrix, can allow the nested list of lists with variable lengths, and when we require the maximizations of its columns, the uneven length of rows may lead to some elements in that elements to be absent and if not handled correctly, may throw an exception. Let’s discuss certain ways in which this pr
6 min read
Python | K length Padding in List
In real world problems, we sometimes require to pad the element of list according to a condition that maximum characters have reached. Padding a number with 0 if it’s length is less than required by any field is one of the basic issues that occur in web forms in Web Development. Let’s discuss certain ways in which this issue can be solved. Method #
8 min read
Python Program to Return the Length of the Longest Word from the List of Words
The problem is to go through all the words in an array and the program should return the word with the longest one. Consider for example we are having an array, and we have numbers in alphabetic form, now when we pass this array as an input then we should get the word with the longest one. Below I had explained it with an example in order to give a
5 min read
Python Program For Finding Length Of A Linked List
Write a function to count the number of nodes in a given singly linked list. For example, the function should return 5 for linked list 1->3->1->2->1. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Iterative Solution: 1) Initialize count as 0 2) Initialize a node pointer, current = head. 3) Do followi
6 min read
Python Program To Check Whether The Length Of Given Linked List Is Even Or Odd
Given a linked list, the task is to make a function which checks whether the length of the linked list is even or odd. Examples: Input : 1->2->3->4->NULL Output : Even Input : 1->2->3->4->5->NULL Output : OddRecommended: Please solve it on "PRACTICE" first, before moving on to the solution. Method 1: Count the codes linea
4 min read
Python Program For Finding The Length Of Loop In Linked List
Write a function detectAndCountLoop() that checks whether a given Linked List contains loop and if loop is present then returns count of nodes in loop. For example, the loop is present in below-linked list and length of the loop is 4. If the loop is not present, then the function should return 0. Recommended: Please try your approach on PRACTICE, b
4 min read
Get Length of a List in Python Without Using Len()
Python len() method is the most common and widely used method for getting the length of a list in Python. But we can use other methods as well for getting the length or size of the list. In this article, we will see how to find the length of a list in Python without using the len() function. Find The Length Of A List In Python Without Using Len()Be
2 min read
Python | Average String length in list
Sometimes, while working with data, we can have a problem in which we need to gather information of average length of String data in list. This kind of information might be useful in Data Science domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + sum() + len() The combination of above func
8 min read
Find length of a string in python (6 ways)
Strings in Python are immutable sequences of Unicode code points. Given a string, we need to find its length. Examples: Input : 'abc' Output : 3 Input : 'hello world !' Output : 13 Input : ' h e l l o ' Output :14 Methods#1: Using the built-in function len. The built-in function len returns the number of items in a container. C/C++ Code # Python co
3 min read
Python | Find whether all tuple have same length
Given a list of tuples, the task is to find whether all tuple have same length. Below are some ways to achieve the above task. Method #1: Using Iteration C/C++ Code # Python code to find whether all # tuple have equal length # Input List initialization Input = [(11, 22, 33), (44, 55, 66)] # printing print("Initial list of tuple", Input) #
6 min read
Find the length of a set in Python
In Python, a Set is a collection data type that is unordered and mutable. A set cannot have duplicate elements. Here, the task is to find out the number of elements present in a set. See the below examples. Examples: Input: a = {1, 2, 3, 4, 5, 6} Output: 6 Input: a = {'Geeks', 'For'} Output: 2 The idea is use len() in Python Example 1: C/C++ Code #
1 min read
Python - Find the sum of Length of Strings at given indices
Given the String list, write a Python program to compute sum of lengths of custom indices of list. Examples: Input : test_list = ["gfg", "is", "best", "for", "geeks"], idx_list = [0, 1, 4] Output : 10 Explanation : 3 + 2 + 5 = 10. (Sizes of strings at idx.) Input : test_list = ["gfg", "is", "best", "for", "geeks"], idx_list = [0, 2, 4] Output : 12
4 min read
Python Program To Find Length Of The Longest Substring Without Repeating Characters
Given a string str, find the length of the longest substring without repeating characters.  For “ABDEFGABEF”, the longest substring are “BDEFGA” and "DEFGAB", with length 6.For “BBBB” the longest substring is “B”, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below diagrams, with length 7 The desired time complexi
6 min read