15.04.2013 Views

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

Core Python Programming (2nd Edition)

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

There is a reversed() built-in function that returns an iterator that traverses an iterable in reverse order.<br />

The enumerate() BIF also returns an iterator. Two new BIFs, any() and all(), made their debut in <strong>Python</strong><br />

2.5they will return true if any or all items traversed across an iterator have a Boolean true value,<br />

respectively. We saw earlier in the chapter how you can use it in a for loop to iterate over both the<br />

index and the item of an iterable. There is also an entire module called itertools that contains various<br />

iterators you may find useful.<br />

8.11.4. Using Iterators with ...<br />

Sequences<br />

As mentioned before, iterating through <strong>Python</strong> sequence types is as expected:<br />

>>> myTuple = (123, 'xyz', 45.67)<br />

>>> i = iter(myTuple)<br />

>>> i.next()<br />

123<br />

>>> i.next()<br />

'xyz'<br />

>>> i.next()<br />

45.67<br />

>>> i.next()<br />

Traceback (most recent call last):<br />

File "", line 1, in ?<br />

StopIteration<br />

If this had been an actual program, we would have enclosed the code inside a try-except block.<br />

Sequences now automatically produce their own iterators, so a for loop:<br />

for i in seq:<br />

do_something_to(i)<br />

under the covers now really behaves like this:<br />

fetch = iter(seq)<br />

while True:<br />

try:<br />

i = fetch.next()<br />

except StopIteration:<br />

break<br />

do_something_to(i)<br />

However, your code does not need to change because the for loop itself calls the iterator's next()<br />

method (as well as monitors for StopIteration).

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

Saved successfully!

Ooh no, something went wrong!