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.

In recent versions of <strong>Python</strong>, though, we no longer need to call the keys method—dictionaries have an iterator that automatically returns one key at a time in aniteration context, so they do not require that the keys list be physically created inmemory all at once. Again, the effect is to optimize execution speed, memory use,and coding effort:>>> for key in D:... print key, D[key]...a 1c 3b 2Other Iteration ContextsSo far, I’ve been demonstrating iterators in the context of the for loop statement,which is one of the main subjects of this chapter. Keep in mind, though, that everytool that scans from left to right across objects uses the iteration protocol. Thisincludes the for loops we’ve seen:>>> for line in open('script1.py'): # Use file iterators... print line.upper( ),...IMPORT SYSPRINT SYS.PATHX = 2PRINT 2 ** 33However, list comprehensions, the in membership test, the map built-in function, andother built-ins, such as the sorted and sum calls, also leverage the iteration protocol:>>> uppers = [line.upper( ) for line in open('script1.py')]>>> uppers['IMPORT SYS\n', 'PRINT SYS.PATH\n', 'X = 2\n', 'PRINT 2 ** 33\n']>>> map(str.upper, open('script1.py'))['IMPORT SYS\n', 'PRINT SYS.PATH\n', 'X = 2\n', 'PRINT 2 ** 33\n']>>> 'y = 2\n' in open('script1.py')False>>> 'x = 2\n' in open('script1.py')True>>> sorted(open('script1.py'))['import sys\n', 'print 2 ** 33\n', 'print sys.path\n', 'x = 2\n']The map call used here, which we’ll meet in the next part of this book, is a tool thatapplies a function call to each item in an iterable object; it’s similar to list comprehensions,but more limited because it requires a function instead of an arbitraryexpression. Because list comprehensions are related to for loops, we’ll explore theseagain later in this chapter, as well as in the next part of the book.Iterators: A First Look | 263

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

Saved successfully!

Ooh no, something went wrong!