7

I would like to do things like this with a for in a single line, can i do it or i have to use a filter?

not 0 <= n <= 255 for n in [-1, 256, 23]
# True
0 <= n <= 255 for n in [0, 255, 256]
# False
0 <= n <= 255 for n in [0, 24, 255]
# True
1
  • 4
    You can use all(..) and any(..) for this. Here you want all, so if all(0 <= n <= 255 for n in [-1,256,23]): Commented Dec 28, 2017 at 22:01

3 Answers 3

9

What you are looking for is all:

all(0 <= n <= 255 for n in [0, 255, 256])
# False
all(0 <= n <= 255 for n in [0, 24, 255])
# True
not all(0 <= n <= 255 for n in [-1, 256, 23])
# True
Sign up to request clarification or add additional context in comments.

Comments

0

I like doing such all-in-range checks like this:

0 <= min(nums) <= max(nums) <= 255

That's usually faster.

Measuring a little:

>>> from timeit import timeit
>>> timeit('0 <= min(nums) <= max(nums) <= 255', 'nums = range(256)')
10.911965313750706
>>> timeit('all(0 <= n <= 255 for n in nums)', 'nums = range(256)')
23.402136341237693

8 Comments

Interesting, given that both min and max have to iterate the collection. Algorithmically 0 <= min(nums) and max(nums) <= 255 should be better..
@schwobaseggl Well, the iterations are simpler (only one comparison for each value), there's no generator overhead, and no Python code runs for each value. I just measured all([0 <= n for n in nums]) and that took 12.7 seconds.
@schwobaseggl Here I did, yes. Python 3.6.1. Why?
About your "and should be better" and also about all having the advantage of being able to stop early: The reason I do this stuff is to catch mistakes in data for coding contests, to ensure that all test data is valid. Which means that I fully expect all values to be in the range and thus fully expect having to run all tests. And I suspect that's quite usual, not just for me and my use cases.
Interesting again, the timings don't care whether range(x) or list(range(x)) is used...
|
0
func = lambda n: 0 <= n <= 255

print(not all(map(func, [-1, 256, 23])))
# True
print(all(map(func, [0, 255, 256])))
# False
print(all(map(func, [0, 24, 255])))
# 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.