How to do it...

  1. The most common use of an interator is to loop through a sequence, printing out each element:
 
    • In the preceding example, we have simply iterated through a variety of sequence containers, specifically a list (line 1), a tuple (line 2), dictionary keys (line 3), characters in a string (line 4), and lines in a file (line 5).
    • While a dictionary is not a sequence type but a mapping type, it does support iteration, as it has an iter() call that is only applicable to a dictionary's keys.
  1. When a for statement is used, it calls the built-in iter() function on the container. The iter() function returns an iterator object that ...

Get Secret Recipes of the Python Ninja now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.