© Joey Bernard 2016

Joey Bernard, Python Recipes Handbook, 10.1007/978-1-4842-0241-8_3

3. Iterators and Generators

Joey Bernard

(1)Fredericton, New Brunswick, Canada

Often you’ll need to process some sequence of data from one source or another. The way to do this in Python is to use iterators. Many of the data types available in standard Python include an iterable interface that you can use. For those that don't, you can create a generator that then provides an iterable interface.

3-1. Iterating Over the Contents of a List

Problem

You want to iterate over the contents of a list.

Solution

While a list is iterable, you need to use the iter function to get access to the associated iterator.

How It Works

Listing 3-1 shows how to get access to the associated ...

Get Python Recipes Handbook: A Problem-Solution Approach 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.