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]