liveBook · Manning

Iterator

As explained in The Quick Python Book, Fourth Edition

An iterator is an object that provides successive values through the iteration protocol until its values are exhausted.

An iterator provides successive values until they are exhausted. In Python, a file object can supply lines to a for loop, while zip() supplies paired values to a CSV writer. section 13.4 section 22.5.2

file_object = open("myfile", 'r')
count = 0
for line in file_object:
   count = count + 1
print(count)
file_object.close()

Count file lines by iterating over the file object; lines are read and processed one at a time. section 13.4

import requests
import csv
response = requests.get("https://archive-api.open-meteo.com/v1/era5?latitude=41.879&longitude=-87.64975
&start_date=2024-07-01&end_date=2024-07-31&daily=temperature_2m_mean")
weather_history = response.json()                            #1
 
weather_data = zip(weather_history["daily"]["time"],  
   weather_history["daily"]["temperature_2m_mean"])          #2
 
with open("weather_history.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Date", "Temperature"])
    writer.writerows(weather_data)                           #3
#1 The response object 's json() method returns data as JSON.
#2 The zip() function returns an iterator of the combined lists.
#3 The writerows() method writes all rows the from iterator weather_data.

zip() pairs weather dates with temperatures, and writerows() consumes the resulting iterator to write CSV rows. section 22.5.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines successive values until exhaustion and demonstrates file and zip() iteration without detailing protocol mechanics.
Examples
Demonstrates counting file lines and writing paired weather dates and temperatures to CSV.
What you can do after
Apply it via for loops and csv.writerows() to process file lines or paired lists.
How it connects
Connects iterators to for loops, file objects, zip(), and CSV writing.

Also explained in

Compare how 15 books explain iterator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.