Change language

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 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method