Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Using Built-in Iterators | Python Iterators
Functional Programming Concepts in Python

bookUsing Built-in Iterators

Swipe to show menu

Python provides several built-in iterators that let you process collections in expressive and memory-efficient ways. Three of the most commonly used are enumerate, zip, and map.

  • enumerate allows you to loop over a sequence while keeping track of both the index and the value of each element;
  • zip lets you iterate over multiple sequences in parallel, pairing elements together;
  • Recall that map is a Higher-Order Function - a concept we used earlier to apply tasks to data. Here, we re-examine this same tool through the iterator protocol. Instead of viewing it simply as a way to process a list, we now see it as a specialized object that produces results on demand, transforming our understanding of map from a static functional tool into a dynamic, memory-efficient stream.

These iterators are invaluable for tasks like processing parallel lists, transforming data, and writing concise loops. As shown in the video, using them properly can simplify your code and reduce errors, especially when working with large or complex data sets.

123456
# Using enumerate and zip to process two lists in parallel names = ["Alice", "Bob", "Charlie"] scores = [85, 92, 78] for idx, (name, score) in enumerate(zip(names, scores), start=1): print(f"{idx}. {name} scored {score}")
copy

In this code, zip(names, scores) pairs each name with its corresponding score, creating an iterator of tuples like ("Alice", 85). Wrapping this with enumerate adds a counter starting at 1, so each iteration provides the index, name, and score. The loop prints each student's name and score, prefixed by their position in the list. This approach is both concise and readable, demonstrating how built-in iterators streamline working with multiple sequences.

question mark

What is the main purpose of using enumerate together with zip in this code sample?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 1

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 5. Chapter 1
some-alt