rickerp
rickerp

Reputation: 123

Python3 - using for loop in a if condition

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

Upvotes: 7

Views: 250

Answers (3)

Menglong Li
Menglong Li

Reputation: 2255

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

Upvotes: 0

Stefan Pochmann
Stefan Pochmann

Reputation: 28656

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

Upvotes: 0

user2390182
user2390182

Reputation: 73498

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

Upvotes: 9

Related Questions