12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

for instead of while whenever possible, and don’t resort to range calls in for loopsexcept as a last resort. This simpler solution is better:>>> for item in X: print item, # Simple iteration...However, the coding pattern used in the prior example does allow us to do more specializedsorts of traversals—for instance, to skip items as we go:>>> S = 'abcdefghijk'>>> range(0, len(S), 2)[0, 2, 4, 6, 8, 10]>>> for i in range(0, len(S), 2): print S[i],...a c e g i kHere, we visit every second item in the string S by stepping over the generated rangelist. To visit every third item, change the third range argument to be 3, and so on. Ineffect, using range this way lets you skip items in loops while still retaining the simplicityof the for.Still, this is probably not the ideal best-practice technique in <strong>Python</strong> today. If youreally want to skip items in a sequence, the extended three-limit form of the sliceexpression, presented in Chapter 7, provides a simpler route to the same goal. Tovisit every second character in S, for example, slice with a stride of 2:>>> for x in S[::2]: print x...Changing Lists: rangeAnother common place where you may use the range and for combination is inloops that change a list as it is being traversed. Suppose, for example, that you needto add 1 to every item in a list for some reason. Trying this with a simple for loopdoes something, but probably not what you want:>>> L = [1, 2, 3, 4, 5]>>> for x in L:... x += 1...>>> L[1, 2, 3, 4, 5]>>> x6This doesn’t quite work—it changes the loop variable x, not the list L. The reason issomewhat subtle. Each time through the loop, x refers to the next integer alreadypulled out of the list. In the first iteration, for example, x is integer 1. In the next iteration,the loop body sets x to a different object, integer 2, but it does not update thelist where 1 originally came from.Loop Coding Techniques | 267

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!