[Tutor] Questions about PIL

Kent Johnson kent37 at tds.net
Thu Nov 9 11:58:06 CET 2006

Chris Hengge wrote:
> alist = difference(image1,image2)
> a = [b for b in alist.getdata() if b != (0,0,0)]
> if len(a) != 0:
>    print "Not the same"
> is much slower then (9x)
> if im1.tostring() != im2.tostring()
>        print "something changed!"

One reason the second version will be faster is that it can stop 
checking for differences as soon as it finds one. The first version will 
look at all of alist.getdata() even if the first entry is not (0, 0, 0). 
If you are using Python 2.5 try
if any(b != (0, 0, 0) for b in alist.getdata()):
   print "Not the same"

This uses a generator comprehension instead of a list comprehension so 
it doesn't have to make the whole list, only enough to find a 
non-(0,0,0) value.

In Python 2.4 you can write it as
for b in alist.getdata():
   if b != (0, 0, 0):
     print "Not the same"

Again the key idea is not to create the entire comparison list if it is 
not needed, and to abort the loop when you find a non-zero entry.


More information about the Tutor mailing list