2

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

Jetman
8934 gold badges19 silver badges34 bronze badges
asked Jan 14, 2019 at 5:00
1
  • I know it's not probably what you want, but for the specific example you give in the question, you could just use chained inequalities 0 <= var - x < 10. Also note that 10 is not included in range(10), so I use < 10 instead of <= 10 which would better match what you say you wanted to do. You may want to use range(11) in the answers below if 10 should be included in the tests. Commented Jan 14, 2019 at 5:23

4 Answers 4

3

Use any this way, also use generator:

if any(var==(x+i) for i in range(10)):
 # do something
answered Jan 14, 2019 at 5:02
Sign up to request clarification or add additional context in comments.

1 Comment

@Retrnon Happy to help, :-), 😊😊😊
0

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.

answered Jan 14, 2019 at 5:16

Comments

0

You can also use this non-any version:

for i in range(10):
 if var == (x+i):
 break
answered Jan 14, 2019 at 5:24

Comments

0

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.

answered Jan 14, 2019 at 6:03

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.