Python | Find all items in a list



Method # 1: Using List Comprehension + len()
We can solve this problem by using list comprehension as a potential shortcut to the usual loops we can be used to accomplish this specific task. We simply iterate over and count the nested list and finally return the cumulative score using the len function.

# Python3 demo code
# count of all items in the list
# Using the comprehension list

 
# initializing list

test_list = [[ 1 , 4 , 5 ], [ 7 , 3 ], [ 4 ], [ 46 , 7 , 3 ]]

 
# print original list

print ( "The original list:" + str ( test_list))

 
# using comprehension list
# count of all items in the list

res = len ([ele for sub in test_list for ele in sub])

  
# print result

print ( "The total element count in lists is:" + str (res))

Output:

 The original list: [[1, 4, 5], [7, 3], [4], [46, 7, 3]] The total element count in lists is: 9 

Method # 2: Using chain () + len ()
This particular the problem can also be solved with a chaining function instead of a list comprehension, in which we use the usual len function to check the length.

# Python3 code to demonstrate walkie talkie
# number of all items in the list
# Using chain () + len ()

from itertools import chain

 
# initializing list

test_list = [[ 1 , 4 , 5 ], [ 7 , 3 ], [ 4 ], [ 46 , 7 , 3 < / code> ]]

 
# print original list

print ( "The original list: " + str (test_list))

 
# using chain () + len ()
# count of all items in the list

res = len ( list (chain ( * test_list)))

 
# print result

print ( "The total element count in lists is:" + str (res))

Output:

 The original list: [[1, 4, 5], [7, 3], [4], [46, 7, 3]] The total element count in lists is: 9