Indexing a list for value within certain range

Viewed 83

I have a list x = [2, 3, 3, 4, 5] and y = [10, 40, 50, 9, 7]. I want to print a list of indices for elements in x and y if x <= 3 and y => 30. So in this case it would be the pairs (3, 40) and (3, 50). Therefore I want a list of their indices as my output. So result = [1, 2].

I tried writing a for loop as follows:

result = []
for i in x, y:
    if x <= 3 and y => 30:
        result.append(enumerate(i))
print(result)
4 Answers

You can use a list comprehension:

result=[i for i in range(len(x)) if x[i] >=3 and y[i]>=30]

print(result)

#[1, 2]

I think this may be what you were aiming at:

>>> result = []
>>> xlist=[2,3,3,4,5]
>>> ylist=[10,40,50,9,7]
>>> for i, (x,y) in  enumerate(zip(xlist,ylist)):
        if x <= 3 and y >= 30:
            result.append(i)
>>> result
[1, 2]

Just to mention another way to achieve this using np.where:

import numpy as np

# need to convert x and y into array first
x = np.array([2, 3, 3, 4, 5])
y = np.array([10, 40, 50, 9, 7])

result = np.where((x >= 3) & (y >= 30))[0].tolist()

print(result)

Assuming x and y are of the same length (otherwise you will have to check which one is shorter):

result=[]
for i in range(len(x)):
    if x[i] <= 3 and y[i] >= 30:
        result.append(i)

print(result)
Related