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
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
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
min and max have to iterate the collection. Algorithmically 0 <= min(nums) and max(nums) <= 255 should be better..all([0 <= n for n in nums]) and that took 12.7 seconds.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.range(x) or list(range(x)) is used...
all(..)andany(..)for this. Here you wantall, soif all(0 <= n <= 255 for n in [-1,256,23]):