Test Your Knowledge: Answers

 

 
  1. The for loop uses the iteration protocol to step through items in the object across which it is iterating. It calls the object’s __next__ method (run by the next built-in) on each iteration and catches the StopIteration exception to determine when to stop looping. Any object that supports this model works in a for loop and in other iteration contexts.
  2. Both are iteration tools. List comprehensions are a concise and efficient way to perform a common for loop task: collecting the results of applying an expression to all items in an iterable object. It’s always possible to translate a list comprehension to a for loop, and part of the list comprehension expression looks like the header of a for loop syntactically.
  3. Iteration contexts in Python include the for loop; list comprehensions; the map built-in function; the in membership test expression; and the built-in functions sorted, sum, any, and all. This category also includes the list and tuple built-ins, string join methods, and sequence assignments, all of which use the iteration protocol (the __next__ method) to step across iterable objects one item at a time.
  4. The best way to read lines from a text file today is to not read it explicitly at all: instead, open the file within an iteration context such as a for loop or list comprehension, and let the iteration tool automatically scan one line at a time by running the file’s next method on each iteration. This approach is generally best in terms of coding simplicity, execution speed, and memory space requirements.
  5. I’ll accept any of the following as correct answers: fear, intimidation, nice red uniforms, a comfy chair, and soft pillows.