In this article we will discuss different ways to count number of elements in a flat list, lists of lists or nested lists.

Count elements in a flat list

Suppose we have a list i.e.

# List of strings
listOfElems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test']

To count the elements in this list, we have different ways. Let’s explore them,

Use len() function to get the size of a list

Python provides a inbuilt function to get the size of a sequence i.e.

len(s)

Arguments:

  • s : A sequence like object like, list, string, bytes, tuple etc.

It returns the length of object i.e. count of elements in the object.

Now let’s use this len() function to get the size of a list i.e.

listOfElems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test']

# Get size of a list using len()
length = len(listOfElems)

print('Number of elements in list : ', length)

Output:
Number of elements in list :  9

How does len() function works ?

When len(s) function is called, it internally calls the __len__() function of the passed object s. Default sequential containers like list, tuple & string has implementation of __len__() function, that returns the count of elements in that sequence.

So, in our case we passed the list object to the len() function. Which internally called the __len__() of the list object, to fetch the count of elements in list.

Use list.__len__() to count elements in a list

We can directly call the __len__() member function of list to get the size of list i.e.

listOfElems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test']

# Get size of a list using list.__len__()
length = listOfElems.__len__()

print('Number of elements in list : ', length)

Output:
Number of elements in list :  9

Although we got the size of list using __len__() function. It is not a recommended way, we should always prefer len() to get the size of list.

Count elements in list of lists

Suppose we have a list of list i.e.

# List of lists
listOfElems2D = [ [1,2,3,45,6,7],
                    [22,33,44,55],
                    [11,13,14,15] ]

Now we want to count all the elements in the list i.e. total numbers in list.

But if we call the len() function on the lists of list i.e.

length = len(listOfElems2D)

print('Number of lists in list = ', length)

Output
Number of lists in list =  3

In case of list of lists, len() returns the number of lists in the main list i.e. 3. But we want to count the total number of elements in the list including these three lists. Let’s see how to do that.

Use for loop to count elements in list of lists

Iterate over the list, add size of all internal lists using len() i.e.

# List of lists
listOfElems2D = [ [1,2,3,45,6,7],
                    [22,33,44,55],
                    [11,13,14,15] ]

# Iterate over the list and add the size of all internal lists 
count = 0
for listElem in listOfElems2D:
    count += len(listElem)                    

print('Total Number of elements : ', count)

Output:
Total Number of elements :  14

Use List comprehension to count elements in list of lists

Iterate over the list of lists using List comprehension. Build a new list of sizes of internal lists. Then pass the list to sum() to get total number of elements in list of lists i.e.

# List of lists
listOfElems2D = [ [1,2,3,45,6,7],
                    [22,33,44,55],
                    [11,13,14,15] ]

# Get the size of list of list using list comprehension & sum() function
count = sum( [ len(listElem) for listElem in listOfElems2D])

print('Total Number of elements : ', count)

Output:
Total Number of elements :  14

Count elements in a nested list

Suppose we have a nested list i.e. a list that contain elements & other lists. Also these internal lists might contain other lists i.e.

# Nested List
nestedList = [2 ,3, [44,55,66], 66, [5,6,7, [1,2,3], 6] , 10, [11, [12, [13, 24]]]]

Now how to calculate the count of number of elements in this kind of nested list ?

For this we have created a recursive function that will use the recursion to go inside this nested list and calculate the total number of elements in it i.e.

def getSizeOfNestedList(listOfElem):
    ''' Get number of elements in a nested list'''
    count = 0
    # Iterate over the list
    for elem in listOfElem:
        # Check if type of element is list
        if type(elem) == list:  
            # Again call this function to get the size of this element
            count += getSizeOfNestedList(elem)
        else:
            count += 1    
    return count

Now let’s use this function to count elements in a nested list i.e.
# Nested List
nestedList = [2 ,3, [44,55,66], 66, [5,6,7, [1,2,3], 6] , 10, [11, [12, [13, 24]]]]

count = getSizeOfNestedList(nestedList)

print('Total Number of elements : ', count)

Output
Total Number of elements :  18

It will iterate over elements in list and for each element it will check if its type is list, then it will again call this function to get the size else returns 1.

Complete example is as follows,

def getSizeOfNestedList(listOfElem):
    ''' Get number of elements in a nested list'''
    count = 0
    # Iterate over the list
    for elem in listOfElem:
        # Check if type of element is list
        if type(elem) == list:  
            # Again call this function to get the size of this element
            count += getSizeOfNestedList(elem)
        else:
            count += 1    
    return count
 
 
def main():
    
    # List of strings
    listOfElems = ['Hello', 'Ok', 'is', 'Ok', 'test', 'this', 'is', 'a', 'test']
 
    print('**** Count number of elements in a flat list ****')
    
    print('** Using len() to get the size of a list **')
    
    # Get size of a list using len()
    length = len(listOfElems)

    print('Number of elements in list : ', length)
 
    print('** Using list.__len__() to get the size of a list **')

    # Get size of a list using list.__len__()
    length = listOfElems.__len__()

    print('Number of elements in list : ', length)
 
    print('**** Count number of elements in list of lists ****')

    # List of lists
    listOfElems2D = [ [1,2,3,45,6,7],
                        [22,33,44,55],
                        [11,13,14,15] ]

    print('Try len() on list of lists')

    length = len(listOfElems2D)

    print('Number of lists in list = ', length)


    print('** Using Iteration to get the number of elements in list of lists **')

    # Iterate over the list and add the size of all internal lists 
    count = 0
    for listElem in listOfElems2D:
        count += len(listElem)                    

    print('Total Number of elements : ', count)
 
    print('** Use List comprehension to get the number of elements in list of lists **')
    
    # Get the size of list of list using list comprehension & sum() function
    count = sum( [ len(listElem) for listElem in listOfElems2D])
 
    print('Total Number of elements : ', count)
 
    print('Using List comprehension')
    count = getSizeOfNestedList(listOfElems2D)
 
    print('Total Number of elements : ', count)
 
    print('**** Count elements in a nested list ****')

    # Nested List
    nestedList = [2 ,3, [44,55,66], 66, [5,6,7, [1,2,3], 6] , 10, [11, [12, [13, 24]]]]

    count = getSizeOfNestedList(nestedList)

    print('Total Number of elements : ', count)
 
    count = getSizeOfNestedList(listOfElems)
 
    print('Total Number of elements : ', count)
 
if __name__ == '__main__':
    main()

Output:
**** Count number of elements in a flat list ****
** Using len() to get the size of a list **
Number of elements in list :  9
** Using list.__len__() to get the size of a list **
Number of elements in list :  9
**** Count number of elements in list of lists ****
Try len() on list of lists
Number of lists in list =  3
** Using Iteration to get the number of elements in list of lists **
Total Number of elements :  14
** Use List comprehension to get the number of elements in list
of lists **
Total Number of elements :  14
Using List comprehension
Total Number of elements :  14
**** Count elements in a nested list ****
Total Number of elements :  18
Total Number of elements :  9

Join a list of 2000+ Programmers for latest Tips & Tutorials