Iterating over a custom ‘Jagged Array’ in Python

A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays." C# natively differentiates between a jagged and a multidimensional array.

To iterate over a every single element of a Jagged Array in Python, you will need to override the default iterator func. I’m simply iterating over 2-levels but you can scale this up to n-levels by using conventional graph traversal algorithms.

class JaggedArray(list):
    ''' An array of arrays! '''

    def __iter__(self):
        if self:
            ptr     = len(self) - 1
            count   = 0

            while count <= ptr:
                item = self[count]

                if isinstance(item, (tuple, list,)):
                    newPtr      = len(item) - 1
                    newCount    = 0

                    while newCount <= newPtr:
                        newItem = item[newCount]
                        yield newItem
                        newCount += 1
                else:
                    yield item

                count += 1

def main():
    obj = JaggedArray()
    obj.append((1, 2, 3,))
    obj.append([4, 5, 6, 7])
    obj.append((8, 9,))

    for item in obj:
        print item,

    raw_input()

if __name__ == '__main__':
    main()

Output >>

1 2 3 4 5 6 7 8 9

leave your comment