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)
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)
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
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
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