Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cyclical indexing of lists in Python

Say I have an array foo with e.g. elements [1, 2, 3], and that I want to retrieve elements of foo as if foo had been "infinitely concatenated".

For example foo[0:2] would return (like a normal list):

[1, 2]

and foo[0:5] would return:

[1, 2, 3, 1, 2]

while foo[7:13] would return:

[2, 3, 1, 2, 3, 1]

Are there any data containers in Python or extended modules that already facilitate this type of access? If not, what would be a good/easy way to provide this container?

like image 330
Amelio Vazquez-Reina Avatar asked Dec 07 '22 08:12

Amelio Vazquez-Reina


1 Answers

I'm afraid you'll have to implement it yourself. It isn't difficult though:

class cyclist(list):
    def __getitem__(self, index):
        return list.__getitem__(self, index % len(self))

    def __getslice__(self, start, stop):
        return [self[n] for n in range(start, stop)]


foo = cyclist([1, 2, 3])
print foo[0:2]    # [1, 2]
print foo[7:13]   # [2, 3, 1, 2, 3, 1]
print foo[0:5]    # [1, 2, 3, 1, 2]

It's missing some details like taking care of omitted slice parameters, negative numbers in slices, and slice step.

like image 145
Pavel Anossov Avatar answered Dec 29 '22 17:12

Pavel Anossov