Python | Index of Non-Zero elements in Python list

Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let’s discuss a shorthand by which we can perform this particular task.

Method : Using enumerate() + list comprehension
This method can be performed using combination of functionalities. In this, we use enumerate function to access index-element together and list comprehension is used for iteration and logic creation.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Index of Non-Zero elements in Python list
# using list comprehension + enumerate()
  
# initialize list
test_list = [6, 7, 0, 1, 0, 2, 0, 12]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Index of Non-Zero elements in Python list
# using list comprehension + enumerate()
res = [idx for idx, val in enumerate(test_list) if val != 0]
  
# printing result
print("Indices of Non-Zero elements : " + str(res))

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.