-4

How to get the index of a number in a python list if we have some condition:

    test_list=[1,5,7,11,20,26,89]
    # find index of number>13

Ans: 4 (index value)

Ironkey
  • 2,568
  • 1
  • 8
  • 30
yashcode17
  • 12
  • 4
  • Did you remember to search before asking? There are a number of suitable solutions in [this](https://stackoverflow.com/questions/2236906/first-python-list-index-greater-than-x) post. – costaparas Jan 09 '21 at 07:43

3 Answers3

3

You can also use numpy in the following way:

import numpy as np
x = np.array([1,5,7,11,20,26,89])
x[np.where(x>13)][0]  # 20

Note that you ask for the index but you wish the value, so in case you wish the index:

np.where(x>13)[0]  # array([4, 5, 6])

will give you all the indices the meets the condition

David
  • 8,113
  • 2
  • 17
  • 36
1

You can simply iterate through the list and break when you condition is true:

test_list = [1,5,7,11,20,26,89]
for i, value in enumerate(test_list):
    if value > 13:
        break

print(value)  # 20
print(i)      # 4
mackorone
  • 1,056
  • 6
  • 15
0

You can use the built-in index method. For example:

test_list = [1,5,7,11,20,26,89]
test_list.index(5)

will return 1. So you can use that in the following manner to get the desired result:

for i in test_list:
    if i > 13:
        print(test_list.index(i))

Edit: Added how to use the index method to meet the requirements of the question

OneCoolBoi
  • 86
  • 5
  • `index()` doesn't get a condition so it won't really help him unless he knows the value – David Jan 09 '21 at 07:31
  • @DavidS I updated my answer to include one of the many ways one can go about using the index method while checking for conditions. – OneCoolBoi Jan 09 '21 at 07:38