Change language

Python | Index of non-null items in a Python list

Method: Using enumerate () + list comprehension
This method can be accomplished using a combination of functions. In this we use the enumeration function to share the index item, and the list comprehension is used to iterate and generate logic.

# Python3 code to demonstrate how it works
# Index of non-null items in the Python list
# using a list comprehension + enumerate ()

 
# initialize the list

test_list = [ 6 , 7 , 0 , 1 , 0 , 2 , 0 , 12 ]

 
# print original list

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

 
# Index of nonzero items in the Python list
# using a list comprehension + enumerate ()

res = [idx for idx, val in enumerate (test_list) if val! = 0 ]

 
# print result

print ( "Indices of Non-Zero elements:" + str (res))

Output:

 The original list is: [6, 7, 0 , 1, 0, 2, 0, 12] Indices of Non-Zero elements: [0, 1, 3, 5, 7] 

Shop

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Best laptop for engineering student

$

Best laptop for development

$

Best laptop for Cricut Maker

$

Best laptop for hacking

$890

Best laptop for Machine Learning

$950

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