...

/

Iterating Idiomatically

Iterating Idiomatically

Learn how to idiomatically iterate in Python.

In this lesson, we'll explore some idioms that come in handy when we have to deal with iteration in Python. These code recipes will help us get a better idea of the types of things we can do with generators, and how to solve typical problems in relation to them.

Idioms for iteration

We are already familiar with the built-in enumerate() function that, given an iterable, will return another one on which the element is a tuple, whose first element is the index of the second one (corresponding to the element in the original iterable):

Press + to interact
print(
list(enumerate("abcdef"))
)

We wish to create a similar object, but in a more low-level fashion: one that can simply create an infinite sequence. We want an object that can produce a sequence of numbers, from a starting one, without any limits.

An object as simple as the following one can do the trick. Every time we call this object, we get the next number of the sequence ad infinitum:

Press + to interact
class NumberSequence:
def __init__(self, start=0):
self.current = start
def next(self):
current = self.current
self.current += 1
return current

Based on ...