Python | Indices of numbers greater than K

Many times we might have problem in which we need to find indices rather than the actual numbers and more often, the result is conditioned. First approach coming to mind can be a simple index function and get indices greater than particular number, but this approach fails in case of duplicate numbers. Let’s discuss certain ways in which this problem can be successfully solved.

Method #1 : Using loop
This problem can easily be solved using loop with a brute force approach in which we can just check for the index as we iterate and append it in a new list as we proceed forward.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# index of matching element using loop
  
# initializing list 
test_list = [12, 10, 18, 15, 8, 18]
  
# printing original list
print("The original list : " + str(test_list))
  
# using loop
# index of matching element
res = []
for idx in range(0, len(test_list)) :
    if test_list[idx] > 10:
        res.append(idx)
  
# print result
print("The list of indices greater than 10 : " + str(res))

chevron_right


Output :



The original list : [12, 10, 18, 15, 8, 18]
The list of indices greater than 10 : [0, 2, 3, 5]

 

Method #2 : Using list comprehension + enumerate()
The combination of these two function can also perform this particular task efficiently and in one line. The enumerate function is used to get element and its index simultaneously.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# index of matching element
# using list comprehension + enumerate()
  
# initializing list 
test_list = [12, 10, 18, 15, 8, 18]
  
# printing original list
print("The original list : " + str(test_list))
  
# using list comprehension + enumerate()
# index of matching element
res = [idx for idx, val in enumerate(test_list) if val > 10]
  
# print result
print("The list of indices greater than 10 : " + str(res))

chevron_right


Output :

The original list : [12, 10, 18, 15, 8, 18]
The list of indices greater than 10 : [0, 2, 3, 5]


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.