Open In App

Python | Program to count number of lists in a list of lists

Last Updated : 28 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list of lists, write a Python program to count the number of lists contained within the list of lists. 

Examples:

Input :  [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
Output : 3
 
Input : [[1], ['Bob'], ['Delhi'], ['x', 'y']]
Output : 4

Method #1 : Using len() 

Python3




# Python3 program to Count number
# of lists in a list of lists
 
 
def countList(lst):
    return len(lst)
 
 
# Driver code
lst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
print(countList(lst))


Output:

3

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

Method #2: Using type() 

Use a for loop and in every iteration to check if the type of the current item is a list or not, and accordingly increment ‘count’ variable. This method has a benefit over approach #1, as it works well for a list of heterogeneous elements. 

Python3




# Python3 program to Count number
# of lists in a list of lists
 
 
def countList(lst):
    count = 0
    for el in lst:
        if type(el) == type([]):
            count += 1
 
    return count
 
 
# Driver code
lst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
print(countList(lst))


Output:

3

Time complexity: O(n), where n is the number of elements in the list.
Auxiliary space: O(1), as we are only using a single variable (count) to store the count of lists.

A one-liner alternative approach for the above code is given below: 

Python3




def countList(lst):
    return sum(type(el)== type([]) for el in lst)


Method #3 : Using isinstance() method 

Python3




# Python3 program to Count number
# of lists in a list of lists
 
def countList(lst):
    return sum(isinstance(i, list) for i in lst)
     
# Driver code
lst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
print(countList(lst))


Output:

3

Time complexity: O(n), where n is the size of the set s.
Auxiliary space: O(n), as we are creating a list x with n elements, where n is the size of the set s.

Method#4: Using the list comprehension

Python3




lst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
x=[i for i in lst]
print(len(x))


Output

3

Time complexity: O(n), where n is the total number of elements in the list of lists.
Auxiliary space: O(n)

Method #5: Using enumerate function 

Python3




lst = ["[1, 2, 3]", "[4, 5]", "[6, 7, 8, 9]"]
x=[list(i) for i in enumerate(lst)]
print(len(x))


Output

3

Time complexity: O(n), where n is length of list.
Auxiliary Space: O(n), where n is length of list.

Method #6: Using lambda function

Python3




lst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
x=list(filter(lambda i: (i),lst))
print(len(x))


Output

3

The time complexity of this code is O(n*m), where n is the number of sublists in the list and m is the average length of the sublists.

The auxiliary space required by this code is also O(n*m), since the filter function creates a new list that contains the same elements as the original list.

Method #7: Using map()

Python3




lst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
x=list(map(str,lst) )
print(len(x))


Output

3

Method #8: Using eval() 

Python3




lst = ["[1, 2, 3]", "[4, 5]", "[6, 7, 8, 9]"]
x=list(map(eval,lst) )
print(len(x))


Output

3

Method #9 : Using recursion

This approach involves reducing the length of the list by 1 at each recursive step and increasing the count by 1 if the first element of the list is a list. The function returns 0 when the list is empty.

Python3




def count_lists(lst):
  if lst == []:
    return 0
  return 1 + count_lists(lst[1:])
 
lst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
print(count_lists(lst))
#This code is contributed by Edula Vinay Kumar Reddy


Output

3

Time complexity: O(n), where n is the total number of elements in the list of lists. This is because the function processes each element of the list exactly once.
Auxiliary space: O(n) as well, since the maximum depth of the recursion tree is n in the worst case. For example, if the list of lists is a list of n single-element lists, the recursion tree will have a maximum depth of n. At each level of the tree, a new frame is added to the call stack, which takes up space in memory.

Method #10: Using ast.literal_eval()

Step-by-step approach:

  • Import the ast module.
  • Define the list of strings, lst.
  • Create an empty list, num_list, to store the converted lists.
  • Loop through each string in lst.
  • Use ast.literal_eval() to convert the string to a list.
  • Append the resulting list to num_list.
  • Calculate the length of num_list using len().
  • Print the length of num_list.

Python3




import ast
 
lst = ["[1, 2, 3]", "[4, 5]", "[6, 7, 8, 9]"]
num_list = []
 
for s in lst:
    num_list.append(ast.literal_eval(s))
 
print(len(num_list))


Output

3

Time complexity: O(n), where n is the length of lst. This is because we loop through each string in lst and apply ast.literal_eval() once for each string.
Auxiliary space: O(n), where n is the length of lst. This is because we create a list of the converted lists, which takes up space in memory.

Method #11: Using functools.reduce()

Step-by-step approach:

  • Initialize a list of lists. 
  • Use reduce method on the list. 
  • reduce method takes a function, list, and initial value as parameters. 
  • reduce iterate over each item of the list and apply a function to it and return value.
  • Function checks are an item an instance of the list or not, if it is then count 1 to the initial value else do nothing. 

Python




# Python3 program to Count number
# of lists in a list of lists
from functools import reduce
 
 
# Function which count the number of list in list
def countList(lst):
    return reduce(lambda a, b : a + 1 if isinstance(b, list) else a, lst, 0)
     
# Driver code
lst = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
print(countList(lst))


Output

3

Time complexity: O(N), where N is the length of the list. 
Auxiliary space: O(1), No extra space is used. 



Similar Reads

Python program to convert a list into a list of lists using a step value
Given a List, the task here is to write a python program that can split the list into list of lists using by a step value here denoted via K. Input : test_list = [5, 6, 3, 2, 7, 1, 9, 10, 8], K = 3Output : [[5, 2, 9], [6, 7, 10], [3, 1, 8]]Explanation : 5, 2 and 9 are 0th, 3rd and 6th element respectively, and hence ( difference 3 ) grouped togethe
4 min read
How to Zip two lists of lists in Python?
The normal zip function allows us the functionality to aggregate the values in a container. But sometimes, we have a requirement in which we require to have multiple lists and containing lists as index elements and we need to merge/zip them together. This is quite uncommon problem, but solution to it can still be handy. Let's discuss certain ways i
7 min read
Python - Convert Lists into Similar key value lists
Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list. Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9] Output : {5: [8], 6: [3, 2, 9]} Explanation : Elements with index 6 in corresponding list, are mapped to 6. Input : test_list1
12 min read
Indexing Lists Of Lists In Python
Lists of lists are a common data structure in Python, providing a versatile way to organize and manipulate data. When working with nested lists, it's crucial to understand how to index and access elements efficiently. In this article, we will explore three methods to index lists of lists in Python using the creation of a sample list, followed by ex
3 min read
Python | Maximum sum of elements of list in a list of lists
Given lists in a list, find the maximum sum of elements of list in a list of lists. Examples: Input : [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]] Output : 33 Explanation: sum of all lists in the given list of lists are: list1 = 6, list2 = 15, list3 = 33, list4 = 24 so the maximum among these is of Input : [[3, 4, 5], [1, 2, 3], [0, 9, 0]] Outpu
4 min read
Python | Ways to sum list of lists and return sum list
The list is an important container and is used almost in every code of day-day programming as well as web development, more it is used, the more is the requirement to master it and hence knowledge of its operations is necessary. Given a list of lists, the program to suppose to return the sum as the final list. Let's see some of the methods to sum a
5 min read
Python | Check if a list exists in given list of lists
Given a list of lists, the task is to check if a list exists in given list of lists. Input : lst = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]] list_search = [4, 5, 6] Output: True Input : lst = [[5, 6, 7], [12, 54, 9], [1, 2, 3]] list_search = [4, 12, 54] Output: False Let’s discuss certain ways in which this task is performed. Method #1: Using
4 min read
Python | Convert list into list of lists
Given a list of strings, write a Python program to convert each element of the given list into a sublist. Thus, converting the whole list into a list of lists. Examples: Input : ['alice', 'bob', 'cara'] Output : [['alice'], ['bob'], ['cara']] Input : [101, 202, 303, 404, 505] Output : [[101], [202], [303], [404], [505]] Approach #1 : Naive Approach
5 min read
Python | Sorting list of lists with similar list elements
Sorting has always been a key operation that is performed for many applications and also as a subproblem to many problems. Many variations and techniques have been discussed and their knowledge can be useful to have while programming. This article discusses the sorting of lists containing a list. Let's discuss certain ways in which this can be perf
5 min read
Python | Merge List with common elements in a List of Lists
Given a list of list, we have to merge all sub-list having common elements. These type of problems are very frequent in College examinations and while solving coding competitions. Below are some ways to achieve this. Input: [[11, 27, 13], [11, 27, 55], [22, 0, 43], [22, 0, 96], [13, 27, 11], [13, 27, 55], [43, 0, 22], [43, 0, 96], [55, 27, 11]] Out
3 min read
Practice Tags :