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.

on any object that is a sequence and, also like the list comprehension, even on somethings that are not. Here, for example, it is stepping across the characters in a string,printing the uppercase version of each as it goes:>>> for c in 'spam':print c.upper( )SPAMWe’ll discuss looping statements further later in the book.Iteration and OptimizationIf the for loop looks like the list comprehension expression introduced earlier, itshould: both are really general iteration tools. In fact, both will work on any objectthat follows the iteration protocol—an idea introduced recently in <strong>Python</strong> that essentiallymeans a physically stored sequence in memory, or an object that generates oneitem at a time in the context of an iteration operation. This is why the sorted callused in the prior section works on the dictionary directly—we don’t have to call thekeys method to get a sequence because dictionaries are iterable objects.I’ll have more to say about the iteration protocol later in this book. For now, keep inmind that any list comprehension expression, such as this one, which computes thesquares of a list of numbers:>>> squares = [x ** 2 for x in [1, 2, 3, 4, 5]]>>> squares[1, 4, 9, 16, 25]can always be coded as an equivalent for loop that builds the result list manually byappending as it goes:>>> squares = []>>> for x in [1, 2, 3, 4, 5]: # This is what a list comp doessquares.append(x ** 2)>>> squares[1, 4, 9, 16, 25]The list comprehension, though, will generally run faster (perhaps even twice asfast)—a property that could matter in your programs for large data sets. Having saidthat, though, I should point out that performance measures are tricky business in<strong>Python</strong> because it optimizes so much, and can vary from release to release.A major rule of thumb in <strong>Python</strong> is to code for simplicity and readability first, andworry about performance later, after your program is working, and after you’veproved that there is a genuine performance concern. More often than not, your codeDictionaries | 83

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

Saved successfully!

Ooh no, something went wrong!