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 example, the following builds a list of the concatenation of x+yfor every x inone string, and every y in another. It effectively collects the permutation of the charactersin two strings:>>> [x + y for x in 'abc' for y in 'lmn']['al', 'am', 'an', 'bl', 'bm', 'bn', 'cl', 'cm', 'cn']Again, one way to understand this expression is to convert it to statement form byindenting its parts. The following is an equivalent, but likely slower, alternative wayto achieve the same effect:>>> res = []>>> for x in 'abc':... for y in 'lmn':... res.append(x + y)...>>> res['al', 'am', 'an', 'bl', 'bm', 'bn', 'cl', 'cm', 'cn']Beyond this complexity level, though, list comprehension expressions can becometoo compact for their own good. In general, they are intended for simple types ofiterations; for more involved work, a simpler for statement structure will probablybe easier to understand and modify in the future. As usual in programming, if somethingis difficult for you to understand, it’s probably not a good idea.We’ll revisit iterators and list comprehensions in Chapter 17, in the context of functionalprogramming tools; as we’ll see, they turn out to be just as related to functionsas they are to looping statements.Chapter SummaryIn this chapter, we explored <strong>Python</strong>’s looping statements as well as some conceptsrelated to looping in <strong>Python</strong>. We looked at the while and for loop statements indepth, and learned about their associated else clauses. We also studied the breakand continue statements, which have meaning only inside loops.Additionally, we took our first substantial look at the iteration protocol in <strong>Python</strong>—away for nonsequence objects to take part in iteration loops—and at list comprehensions.As we saw, list comprehensions, which apply expressions to all the items inany iterable object, are similar to for loops.This wraps up our tour of specific procedural statements. The next chapter closesout this part of the book by discussing documentation options for <strong>Python</strong> code.Documentation is also part of the general syntax model, and it’s an importantcomponent of well-written programs. In the next chapter, we’ll also dig into a set ofexercises for this part of the book before we turn our attention to larger structuressuch as functions. As always, though, before moving on, first exercise what you’vepicked up here with a quiz.Chapter Summary | 275

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

Saved successfully!

Ooh no, something went wrong!