A list is a collection data type that is ordered and changeable. A list can have duplicate entries as well. Here, the task is to find the number of entries in a list in Python.
Examples:
Input: a = [1, 2, 3, 1, 2, 3]
Output: 6
Explanation: The output is 6 because the number of entries in the list a is also 6.
Find the Length of a List in Python
Below are the methods that we will cover in this article:
Find the size of the list using the len() method
The len() works in O(1) time as the list is an object and has a member to store its size. Below is a description of len() from Python docs.
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
# Python program to demonstrate working of len() a = []
a.append( "Hello" )
a.append( "Geeks" )
a.append( "For" )
a.append( "Geeks" )
print ( "The length of list is: " , len (a))
|
The length of list is: 4
Find the length of a list using the sum() function
Another approach is to use the built-in sum() function in combination with a generator expression. This allows you to find the size of a list by summing the number of elements in the list that meet a certain condition.
# list of numbers numbers = [ 1 , 2 , 3 , 1 , 2 , 3 ]
# find the size of the list size = sum ( 1 for num in numbers)
# print the size of the list print (size)
|
6
This will output 6 because the list contains 6 elements.
Time complexity: The time complexity of the approach using the sum() function and a generator expression is O(n), where n is the length of the list.
Space complexity: The auxiliary space complexity of this approach is O(1) because the generator expression only requires a single variable to store the current element being processed.
Find the length of the list using for loop
In this way, we initialize a variable count and then we increment the variable through the loop, and by the end of the loop we get the length of the list in our count variable.
lst = [ 1 , 1 , 2 , 5 , 1 , 5 , 2 , 4 , 5 ]
count = 0
for i in lst:
count + = 1
print ( "The length of the lst is :" ,count)
|
The length of the lst is : 9
Time Complexity: O(n)
Space Complexity: O(1)
Find the size of the list using the length_hint()
method
The length_hint()
function from the operator
module to estimate the length of a list. However, please note that this function is not guaranteed to give you the exact size of the list, especially for standard Python lists.
The length_hint()
the function provides a hint about the expected length of an iterable, but it might not be accurate for all types of iterables. Here’s your example:
from operator import length_hint
lst = [ 'Geeks' , 'For' , 'Geeks' ]
size = length_hint(lst)
print ( 'The size of the size lst:' ,size)
|
The size of the size lst: 3
Time Complexity: O(n)
Space Complexity: O(1)