Trying to iterate over range of numbers (or list) to check if values are equal. Seems very simple, but I cant seem to find a way to do it.
I am trying to use an if statement to check scope of items in a 2D array.
# check if x is equal to var if added to any number between 0 and 10.
if var == x + any(range(10)): # not how it works, but how I want it to
# do something
After looking into any() I realize that It just returns True if any item in the iterate is True
4 Answers 4
Use any this way, also use generator:
if any(var==(x+i) for i in range(10)):
# do something
1 Comment
You have to use several Python functions for that:
if var in list(map(lambda item: x+item, range(10)))
list: Casts the parameter into a list object.
map: Applies a function (first parameter) to a collection of values (second parameter).
lambda: Lambda function.
Comments
You can also use this non-any version:
for i in range(10):
if var == (x+i):
break
Comments
Another way to do it using numpy:
import numpy as np
if var in x + np.arange(10) :
# do something
Would suffer from floating point problem if your numbers are not integers.
0 <= var - x < 10. Also note that10is not included inrange(10), so I use< 10instead of<= 10which would better match what you say you wanted to do. You may want to userange(11)in the answers below if 10 should be included in the tests.