Online Book Reader

Home Category

Learning Python - Mark Lutz [201]

By Root 1339 0
at offset 2

m appears at offset 3

The enumerate function returns a generator object—a kind of object that supports the iteration protocol that we will study in the next chapter and will discuss in more detail in the next part of the book. In short, it has a __next__ method called by the next built-in function, which returns an (index, value) tuple each time through the loop. We can unpack these tuples with tuple assignment in the for loop (much like using zip):

>>> E = enumerate(S)

>>> E

>>> next(E)

(0, 's')

>>> next(E)

(1, 'p')

>>> next(E)

(2, 'a')

As usual, we don’t normally see this machinery because iteration contexts—including list comprehensions, the subject of Chapter 14—run the iteration protocol automatically:

>>> [c * i for (i, c) in enumerate(S)]

['', 'p', 'aa', 'mmm']

To fully understand iteration concepts like enumerate, zip, and list comprehensions, we need to move on to the next chapter for a more formal dissection.

Chapter Summary

In this chapter, we explored Python’s looping statements as well as some concepts related to looping in Python. We looked at the while and for loop statements in depth, and we learned about their associated else clauses. We also studied the break and continue statements, which have meaning only inside loops, and met several built-in tools commonly used in for loops, including range, zip, map, and enumerate (although their roles as iterators in Python 3.0 won’t be fully uncovered until the next chapter).

In the next chapter, we continue the iteration story by discussing list comprehensions and the iteration protocol in Python—concepts strongly related to for loops. There, we’ll also explain some of the subtleties of iterable tools we met here, such as range and zip. As always, though, before moving on let’s exercise what you’ve picked up here with a quiz.

Test Your Knowledge: Quiz

What are the main functional differences between a while and a for?

What’s the difference between break and continue?

When is a loop’s else clause executed?

How can you code a counter-based loop in Python?

What can a range be used for in a for loop?

Test Your Knowledge: Answers

The while loop is a general looping statement, but the for is designed to iterate across items in a sequence (really, iterable). Although the while can imitate the for with counter loops, it takes more code and might run slower.

The break statement exits a loop immediately (you wind up below the entire while or for loop statement), and continue jumps back to the top of the loop (you wind up positioned just before the test in while or the next item fetch in for).

The else clause in a while or for loop will be run once as the loop is exiting, if the loop exits normally (without running into a break statement). A break exits the loop immediately, skipping the else part on the way out (if there is one).

Counter loops can be coded with a while statement that keeps track of the index manually, or with a for loop that uses the range built-in function to generate successive integer offsets. Neither is the preferred way to work in Python, if you need to simply step across all the items in a sequence. Instead, use a simple for loop instead, without range or counters, whenever possible; it will be easier to code and usually quicker to run.

The range built-in can be used in a for to implement a fixed number of repetitions, to scan by offsets instead of items at offsets, to skip successive items as you go, and to change a list while stepping across it. None of these roles requires range, and most have alternatives—scanning actual items, three-limit slices, and list comprehensions are often better solutions today (despite the natural inclinations of ex-C programmers to want to count things!).

Chapter 14. Iterations and Comprehensions, Part 1

In the prior chapter we met Python’s two looping statements, while and for. Although they can handle most repetitive tasks programs need to perform, the need to iterate over sequences is so common and pervasive

Return Main Page Previous Page Next Page

®Online Book Reader