Copying sections of one picture to another I have two solutions (in Jython) to take two pictures and copy and paste alternate sections of one picture to the other, like so:



for x in range (0,w):
  for y in range (0,h):
    sourcePx=getPixel(pic1,x,y)
    targetPx=getPixel(pic2,x,y)
    if (y&gt;=0 and y&lt;20) or (y&gt;=40 and y&lt;60)or (y&gt;=80 and y&lt;=100):
      setColor(targetPx, getColor(sourcePx))
repaint (pic2)




for y in range(0,h):
  leaf = (y&gt;=0 and y&lt;20) or (y&gt;=40 and y&lt;60)or (y&gt;=80 and y&lt;=100):
  if leaf:
    for x in range(width):
      sourcePx = getPixel(pic1, x, y)
      targetPx = getPixel(pic2, x, y)
      setColor(targetPx, getColor(sourcePx))
  repaint(pic2)




I have been trying to work this out and have two questions about this:


Which is the more efficient way to loop through the pixels and why?
Does it make any difference to efficiency (and if so how), creating the variable leaf and then using that in the if statement?
The second one is more efficient. Simply because in the first one you are calculating the if w * h times but in the second you are calculating it h times.

Also it can be made more readable and efficient just by using this. It eliminates leaf which you aren't using anywhere. Readability doesn't need explaining. 

for y in range(0,h):
  if (20 &gt; y &gt;= 0) or (60 &gt; y &gt;= 40)or (100 &gt;= y &gt;= 80):
    for x in range(width):
      sourcePx = getPixel(pic1, x, y)
      targetPx = getPixel(pic2, x, y)
      setColor(targetPx, getColor(sourcePx))
  repaint(pic2)


Update 1

As limelights has suggested, use of xrange is better than use of range in Python2. If your h or w are big then using range would return a list which occupies memory while use of xrange returns a generator which is much more memory efficient. Performance might suffer a bit but in most cases it is worth it.