12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Loop Coding TechniquesThe for loop subsumes most counter-style loops. It’s generally simpler to code andquicker to run than a while, so it’s the first tool you should reach for whenever youneed to step through a sequence. But there are also situations where you will need toiterate in more specialized ways. For example, what if you need to visit every secondor third item in a list, or change the list along the way? How about traversing morethan one sequence in parallel, in the same for loop?You can always code such unique iterations with a while loop and manual indexing,but <strong>Python</strong> provides two built-ins that allow you to specialize the iteration in a for:• The built-in range function returns a list of successively higher integers, whichcan be used as indexes in a for. *• The built-in zip function returns a list of parallel-item tuples, which can be usedto traverse multiple sequences in a for.Because for loops typically run quicker than while-based counter loops, it’s to youradvantage to use tools that allow you to use for when possible. Let’s look at each ofthese built-ins in turn.Counter Loops: while and rangeThe range function is really a general tool that can be used in a variety of contexts.Although it’s used most often to generate indexes in a for, you can use it anywhereyou need a list of integers:>>> range(5), range(2, 5), range(0, 10, 2)([0, 1, 2, 3, 4], [2, 3, 4], [0, 2, 4, 6, 8])With one argument, range generates a list of integers from zero up to but not includingthe argument’s value. If you pass in two arguments, the first is taken as the lowerbound. An optional third argument can give a step; if used, <strong>Python</strong> adds the step toeach successive integer in the result (steps default to 1). Ranges can also be nonpositiveand nonascending, if you want them to be:>>> range(-5, 5)[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]>>> range(5, -5, -1)[5, 4, 3, 2, 1, 0, -1, -2, -3, -4]* <strong>Python</strong> today also provides a built-in called xrange that generates indexes one at a time instead of storing allof them in a list at once like range does. There’s no speed advantage to xrange, but it’s useful as a space optimizationif you have to generate a huge number of values. At this writing, however, it seems likely that xrangemay disappear in <strong>Python</strong> 3.0 altogether, and that range may become a generator object that supports the iterationprotocol to produce one item at a time, instead of all at once in a list; check the 3.0 release notes forfuture developments on this front.Loop Coding Techniques | 265

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

Saved successfully!

Ooh no, something went wrong!