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.

es = []>>> for x in L:... res.append(x + 10)...>>> res[21, 22, 23, 24, 25]In fact, this is exactly what the list comprehension does internally.However, list comprehensions are more concise to write, and because this code patternof building up result lists is so common in <strong>Python</strong> work, they turn out to be veryhandy in many contexts. Moreover, list comprehensions can run much faster thanmanual for loop statements (in fact, often roughly twice as fast) because their iterationsare performed at C language speed inside the interpreter, rather than withmanual <strong>Python</strong> code; especially for larger data sets, there is a major performanceadvantage to using them.Using List Comprehensions on FilesLet’s work through another common use case for list comprehensions to explorethem in more detail. Recall that the file object has a readlines method that loads thefile into a list of line strings all at once:>>> f = open('script1.py')>>> lines = f.readlines( )>>> lines['import sys\n', 'print sys.path\n', 'x = 2\n', 'print 2 ** 33\n']This works, but the lines in the result all include the newline character (\n) at theend. For many programs, the newline character gets in the way—we have to be carefulto avoid double-spacing when printing, and so on. It would be nice if we couldget rid of these newlines all at once, wouldn’t it?Any time we start thinking about performing an operation on each item in asequence, we’re in the realm of list comprehensions. For example, assuming thevariable lines is as it was in the prior interaction, the following code does the job byrunning each line in the list through the string rstrip method to remove whitespaceon the right side (a line[:-1] slice would work, too, but only if we can be sure alllines are properly terminated):>>> lines = [line.rstrip( ) for line in lines]>>> lines['import sys', 'print sys.path', 'x = 2', 'print 2 ** 33']This works, but because list comprehensions are another iteration context just likesimple for loops, we don’t even have to open the file ahead of time. If we open itinside the expression, the list comprehension will automatically use the iteration protocolwe met earlier in this chapter. That is, it will read one line from the file at atime by calling the file’s next method, run the line through the rstrip expression,List Comprehensions: A First Look | 273

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

Saved successfully!

Ooh no, something went wrong!