2

Meaning "if each item is within range of other item with the same index".

price = [1, 2]  
budget = [5, 7]

This works:

if price[0] in range(budget[0]) and price[1] in range(budget[1]):
    affordable = True

I figure there's some way to just reference the whole array though. Like so: if price in budget:

2
  • What exactly do you mean, "within range"? What is a range of a single item? What determines whether the price is "in budget" here? Commented Feb 20, 2017 at 9:36
  • 1
    You can use all; e.g. if all(price[i] in range(budget[i]) for i in range(...)) or all(p in range(b) for p,b in zip(price, budget)) if that's what you really want. Commented Feb 20, 2017 at 9:36

2 Answers 2

5

You could use:

if all(x in range(y) for x,y in zip(price,budget)):
    affordable = True

This will create tuples of price[i],budget[i] and then for each of these tuples we check that price[i] is in range(budget[i]). Nevertheless, you can optimize this further to:

if all(0 <= x < y for x,y in zip(price,budget)):
    affordable = True

Note that this makes the assumption that prices are all integers. If you however use x in range(y) it will fail if x is not an integer. So 0.7 in range(10) would fail whereas our second approach will succeed (but it depends of course on what you want).

Sign up to request clarification or add additional context in comments.

6 Comments

Using range would also fail if budget isn't an integer
0<=x<=y (or similar) instead of x in range(y) will deal with floats and not compile (and iterate; PY2) a list
That'd do it, thanks :) I just remembered what I actually need in my case was to check for either instead of both, here's how to do it in that case: if any(x not in range(y) for x, y in zip(price, budget)):
@schwobaseggl: what do you mean with "not compile"?
@WillemVanOnsem In Python2, range builds (compiles) a list of integers first, and then must iterate it again for the contains check, which seems like a lot work to check if some numerical values lies between two other numerical values. compile = build, put together, not in the computational sense of 'translate' ;)
|
2

Assuming that both prices and budgets must be non-negative, using in range seems to be over-complicating things. Instead, you could just use the < operator.

Regardless of whether you use < or in range, it seems like the easiest approach would be to zip both lists and apply the condition on the pairs:

if (all([x[0] >= x[1] for x in zip(budget, price)])):
    affordable = True

Comments

Your Answer

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.