Indexable iterables
Learn how objects are automatically iterable if you implement integer indexing. Introduction An iterable in Python is any object you can traverse through with a for loop. Iterables are typically co...

Source: mathspp.com
Learn how objects are automatically iterable if you implement integer indexing. Introduction An iterable in Python is any object you can traverse through with a for loop. Iterables are typically containers and iterating over the iterable object allows you to access the elements of the container. This article will show you how you can create your own iterable objects through the implementation of integer indexing. Indexing with __getitem__ To make an object that can be indexed you need to implement the method __getitem__. As an example, you'll implement a class ArithmeticSequence that represents an arithmetic sequence, like \(5, 8, 11, 14, 17, 20\). An arithmetic sequence is defined by its first number (\(5\)), the step between numbers (\(3\)), and the total number of elements (\(6\)). The sequence \(5, 8, 11, 14, 17, 20\) is seq = ArithmeticSequence(5, 3, 6) and seq[3] should be \(14\). Using some arithmetic, you can implement indexing in __getitem__ directly: class ArithmeticSequence: