Using 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.
enumerateallows you to loop over a sequence while keeping track of both the index and the value of each element;ziplets you iterate over multiple sequences in parallel, pairing elements together;- Recall that
mapis 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 ofmapfrom 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.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat