Python | Program to count number of lists in a list of lists
Last Updated :
28 Apr, 2023
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
def countList(lst):
return len (lst)
lst = [[ 1 , 2 , 3 ], [ 4 , 5 ], [ 6 , 7 , 8 , 9 ]]
print (countList(lst))
|
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
def countList(lst):
count = 0
for el in lst:
if type (el) = = type ([]):
count + = 1
return count
lst = [[ 1 , 2 , 3 ], [ 4 , 5 ], [ 6 , 7 , 8 , 9 ]]
print (countList(lst))
|
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
def countList(lst):
return sum ( isinstance (i, list ) for i in lst)
lst = [[ 1 , 2 , 3 ], [ 4 , 5 ], [ 6 , 7 , 8 , 9 ]]
print (countList(lst))
|
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))
|
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))
|
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))
|
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))
|
Method #8: Using eval()
Python3
lst = [ "[1, 2, 3]" , "[4, 5]" , "[6, 7, 8, 9]" ]
x = list ( map ( eval ,lst) )
print ( len (x))
|
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))
|
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))
|
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
from functools import reduce
def countList(lst):
return reduce ( lambda a, b : a + 1 if isinstance (b, list ) else a, lst, 0 )
lst = [[ 1 , 2 , 3 ], [ 4 , 5 ], [ 6 , 7 , 8 , 9 ]]
print (countList(lst))
|
Time complexity: O(N), where N is the length of the list.
Auxiliary space: O(1), No extra space is used.
Similar Reads
Python - Convert List of lists to list of Sets
We are given a list containing lists, and our task is to convert each sublist into a set. This helps remove duplicate elements within each sublist. For example, if we have: a = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]] The output should be: [{1, 2}, {1, 2, 3}, {2}, {0}] Let's explore some method's t
2 min read
Python | Program to count duplicates in a list of tuples
Given a list of tuples, write a Python program to check if an element of the list has duplicates. If duplicates exist, print the number of occurrences of each duplicate tuple, otherwise print "No Duplicates". Examples: Input : [('a', 'e'), ('b', 'x'), ('b', 'x'), ('a', 'e'), ('b', 'x')] Output : ('a
6 min read
Python | Convert list of tuples to list of list
Converting list of tuples to list of lists in Python is a task where each tuple is transformed into list while preserving its elements. This operation is commonly used when we need to modify or work with the data in list format instead of tuples. Using numpyNumPy makes it easy to convert a list of t
3 min read
Python program to find number of local variables in a function
Given a Python program, task is to find the number of local variables present in a function. Examples: Input : a = 1 b = 2.1 str = 'GeeksForGeeks' Output : 3 We can use the co_nlocals() function which returns the number of local variables used by the function to get the desired result. Code #1: # Im
1 min read
Convert Set of Tuples to a List of Lists in Python
Sets and lists are two basic data structures in programming that have distinct uses. It is sometimes necessary to transform a collection of tuples into a list of lists. Each tuple is converted into a list throughout this procedure, and these lists are subsequently compiled into a single, bigger list
3 min read
Python - Convert a list into tuple of lists
When working with data structures in Python, there are times when we need to convert a list into a tuple of smaller lists. For example, given a list [1, 2, 3, 4, 5, 6], we may want to split it into a tuple of two lists like ([1, 2, 3], [4, 5, 6]). We will explore different methods to achieve this co
3 min read
Python Program to Count the Number of Vowels in a String
In this article, we will be focusing on how to print each word of a sentence along with the number of vowels in each word using Python. Vowels in the English language are: 'a', 'e', 'i', 'o', 'u'. So our task is to calculate how many vowels are present in each word of a sentence. So let us first des
10 min read
Python program to get the indices of each element of one list in another list
Given 2 lists, get all the indices of all occurrence of each element in list2 from list1. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 4] Output : [[3], [1, 9], [0, 7]] Explanation : 5 is present at 1st and 9th index. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5,
7 min read
Python program to calculate the number of digits and letters in a string
In this article, we will check various methods to calculate the number of digits and letters in a string. Using a for loop to remove empty strings from a list involves iterating through the list, checking if each string is not empty, and adding it to a new list. [GFGTABS] Python s = "Hello123!
3 min read
Python program to get all unique combinations of two Lists
The goal is to combine each item from first list with each item from second list in every possible unique way. If we want to get all possible combinations from two lists. Pythonâs itertools library has a function called a product that makes it easy to generate combinations of items from multiple lis
2 min read