Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to create an array (or matrix) that is circular, like:

 a = [1,2,3]

From the above list, I want to create the below list:

a[0] = 1

a[1] = 2

a[2] = 3

a[3] = 1

a[4] = 2

#Etc for all index values of a.

Why I want to do that is because I am having a picture as a matrix and I want to process it in a way that if it is not working from one direction, it should reappear on the opposite side.

1 Answer

0 votes
by (108k points)
edited by

In that case, you can simply use the modulo operator:

print a[3 % len(a)] 

Let's say you do not want to use the operator, then you can use the subclass list and implement __getitem__():

class CustomList(list):

    def __getitem__(self, index):

        return super(CustomList, self).__getitem__(index % len(self))

a = CustomList([1, 2, 3])

for index in xrange(5):

    print index, a[index]

Output

0 1

1 2

2 3

3 1

4 2

If you want to proceed with the Numpy Arrays package, then refer to the below code:

import numpy as np

class CustomArray(np.ndarray):

    def __new__(cls, *args, **kwargs):

        return np.asarray(args[0]).view(cls)

    def __getitem__(self, index):

        return np.ndarray.__getitem__(self, index % len(self))

a = CustomArray([1, 2, 3])

for index in xrange(5):

    print a[index]

If you are a beginner and want to know more about Python, then do refer to the Python certification course. 

Related questions

0 votes
1 answer
asked Sep 17, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...