Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: combining less than (<) operator with `and` key word?

I'm reading the docs of PIL, Link, and I found this line

mask = source[R].point(lambda i: i < 100 and 255)

So what does it mean that i < 100 and 255?

like image 547
Rainning Avatar asked Aug 09 '26 18:08

Rainning


1 Answers

This is featured in the paragraph right after:

Python only evaluates the portion of a logical expression as is necessary to determine the outcome, and returns the last value examined as the result of the expression. So if the expression above is false (0), Python does not look at the second operand, and thus returns 0. Otherwise, it returns 255.

If i < 100 is True, it returns 255. This makes sense considering the whole RGB colour scheme where RGB(255, 0, 0) returns Red.


But yes, this is bad practise. It should be:

mask = source[R].point(lambda i: 255 if i < 100 else 0)

Much more readable...

like image 141
TerryA Avatar answered Aug 11 '26 09:08

TerryA