Tag Archives: iterate in Python

How to iterate over data that has no iterator in Python

Data structures in Python are almost entirely already iterable. However, sometimes you do need a generator for the cases when the data is not iterable.

A generator is just a function that yields back to the section where it was called from. This is a signal for Python that you want to create a generator therefore it will automatically save the state of the function at the point of the yield statement. At this point you can return to it when next() is called.

A classic example will be a generator that generates the sequence of squares.

>>> def squares(value = 5):
... 	while True:
... 		value = value + 1
... 		yield (value - 1) * (value - 1)
>>> generator = squares()
>>> next(generator)
>>> next(generator)
>>> next(generator)

Continue reading

How to iterate over the content of a list in Python

Let’s say that you need to iterate over the content of a list. In order to do that you need to use the iter function that allows you to get access to the associated iterator.

>>> list_one = [1, 2, 3, 4]
>>> iterator_one = iter(list_one)
>>> iterator_one

Continue reading