How can you process a list one item at a time? An iterator supplies successive items. Call iter on an iterable to obtain an iterator, then call next to retrieve each item. Once there are no items left, next raises StopIteration. section 5.1.1
Retrieve items one by one
tasks = ["task0", "task1", "task2"] tasks_iterator = iter(tasks) next(tasks_iterator) # 'task0' next(tasks_iterator) # 'task1' next(tasks_iterator) # 'task2' next(tasks_iterator) # raises StopIteration Each call advances through the available items. Usually, a for loop is simpler: `for task in tasks: print(task)` prints the three tasks and exits normally when the iterator is exhausted. section 5.1.1
You rarely need to create an iterator explicitly. A for loop handles iterator creation and StopIteration for you. Functions can also return iterators that fit directly into a loop. section 5.1.1 section 5.3.2
Choose the iterator-producing function that matches the task:
- `reversed(tasks)` supplies list items in reverse order without calculating indexes. section 5.3.2
- `zip(tasks, dates, locations)` supplies tuples of aligned items; unpack each tuple in the loop. By default, zip stops when the shortest iterable is exhausted. section 5.3.3
- `list(map(float, numbers_str))` collects the converted values produced by a map iterator. section 5.1.3
Consume a CSV header separately
For a CSV file whose first row contains field names: with open("tasks.txt", newline="") as file: csv_reader = csv.reader(file) fields = next(csv_reader) for row in csv_reader: print(dict(zip(fields, row))) After next consumes the header, the loop begins with the second row. A file with columns `task_id,title,urgency` can produce `{'task_id': '1001', 'title': 'Homework', 'urgency': '5'}`. If the goal is simply to read header-based rows as dictionaries, `csv.DictReader(file)` is cleaner. section 11.2.2














