Python iterating over matrix class
<pre><code>from collections.abc import Sequence

class Map(Sequence):
    """ Represents a map for a floor as a matrix """

    def __init__(self, matrix):
        """ Takes a map as a matrix """
        self.matrix = matrix
        self.height = len(matrix)
        self.width = len(matrix[0])
        super().__init__()

    def __getitem__(self, item):
        """ Needed by Sequence """
        return self.matrix[item]

    def __len__(self):
        """ Needed by Sequence """
        return len(self.matrix)

    def search(self, entity):
        """ Returns a generator of tuples that contain the x and y for every element in the map that matches 'entity' """
        for row in range(self.height):
            for column in range(self.width):
                if matrix[row][column] == entity:
                    yield (row, column)


# Examples

gmap = Map([[0, 0, 0],
           [0, 1, 0],
           [0, 0, 0]])

for entity in gmap:
    print(entity)
</code></pre>

<p>How can I implement<code>__iter__</code> so that </p>

<pre><code>for entity in gmap:
    print(entity)
</code></pre>

<p>yields <code>0 0 0 0 1 0 0 0 0</code> and not </p>

<pre><code>[0, 0, 0]
[0, 1, 0]
[0, 0, 0]
</code></pre>

<p>This would save me from needing to subclass <code>Sequence</code> and would make the code for <code>search()</code> neater</p>

<p>Additionally, are their any other magic methods I should be using? (aside from <code>__str__</code>, im doing that after I get iterating working)</p>

<p>You may implement <code>__iter__()</code> like so:</p>

<pre><code>from itertools import chain

def __iter__(self):
    return chain.from_iterable(self.matrix)
</code></pre>

<p><code>itertools.chain.from_iterable()</code> takes an iterable of iterables and combines them all together. It creates a generator thus does not use extra memory.</p>

python class iterable