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

Using Built-in Iterators

Svep för att visa menyn

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}")

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?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 5. Kapitel 1

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 5. Kapitel 1
some-alt