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.

Moreover, the iterator version has been greatly optimized by <strong>Python</strong>, so it should runfaster as well.As mentioned in the earlier sidebar “Why You Will Care: File Scanners,” it’s alsopossible to read a file line by line with a while loop:>>> f = open('script1.py')>>> while True:... line = f.readline( )... if not line: break... print line.upper( ),......same output...However, this will likely run slower than the iterator-based for loop version becauseiterators run at C language speed inside <strong>Python</strong>, whereas the while loop version runs<strong>Python</strong> byte code through the <strong>Python</strong> virtual machine. Any time we trade <strong>Python</strong>code for C code, speed tends to increase.Other Built-in Type IteratorsTechnically, there is one more piece to the iteration protocol. When the for loopbegins, it obtains an iterator from the iterable object by passing it to the iter built-infunction; the object returned has the required next method. This becomes obvious ifwe look at how for loops internally process built-in sequence types such as lists:>>> L = [1, 2, 3]>>> I = iter(L) # Obtain an iterator object>>> I.next( ) # Call next to advance to next item1>>> I.next( )2>>> I.next( )3>>> I.next( )Traceback (most recent call last):File "", line 1, in I.next( )StopIterationBesides files and physical sequences like lists, other types have useful iterators aswell. The classic way to step through the keys of a dictionary, for example, is torequest its keys list explicitly:>>> D = {'a':1, 'b':2, 'c':3}>>> for key in D.keys( ):... print key, D[key]...a 1c 3b 2262 | Chapter 13: while and for Loops

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

Saved successfully!

Ooh no, something went wrong!