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.

Generating Both Offsets and Items: enumerateEarlier, we discussed using range to generate the offsets of items in a string, ratherthan the items at those offsets. In some programs, though, we need both: the item touse, plus an offset as we go. Traditionally, this was coded with a simple for loop thatalso kept a counter of the current offset:>>> S = 'spam'>>> offset = 0>>> for item in S:... print item, 'appears at offset', offset... offset += 1...s appears at offset 0p appears at offset 1a appears at offset 2m appears at offset 3This works, but in more recent <strong>Python</strong> releases, a new built-in named enumerate doesthe job for us:>>> S = 'spam'>>> for (offset, item) in enumerate(S):... print item, 'appears at offset', offset...s appears at offset 0p appears at offset 1a appears at offset 2m appears at offset 3The enumerate function returns a generator object—a kind of object that supports theiteration protocol we met earlier in this chapter, and will discuss in more detail in thenext part of the book. It has a next method that returns an (index, value) tuple eachtime through the list, which we can unpack with tuple assignment in the for (muchlike using zip):>>> E = enumerate(S)>>> E.next( )(0, 's')>>> E.next( )(1, 'p')As usual, we don’t normally see this machinery because iteration contexts—includinglist comprehensions, the subject of the next section—run the iteration protocolautomatically:>>> [c * i for (i, c) in enumerate(S)]['', 'p', 'aa', 'mmm']Loop Coding Techniques | 271

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

Saved successfully!

Ooh no, something went wrong!