How to check if an integer is greater than another by a certain value in python?

Viewed 32

How could I check if the integers in y are greater than x by 2 or more?

For example if I have these variables and want to only return 7 and 10:

x = 3
y = [1,3,4,7,10]

4 Answers
x = 3
y = [1,3,4,7,10]

out = [] # list to store values

# Make a loop
for v in y:
    if v - x >= 2: # check if greater than x by 2 or more
        out.append(v) # store value

You can simply do

x = 3
y = [1,3,4,7,10]
threshold = 2
print([ele for ele in y if (ele-x) >= threshold])

Add 2 to x and compare with that.

x = 3
x_plus_2 = x + 2

result = [item for item in y if item >= x_plus_s]

You can use the NumPy package like this:

import numpy as np
x = 3
# Convert y to NumPy array
y = np.array([1,3,4,7,10])
y[y >= x+2]
Related