Wrapping Around on a List When List Index Is Out of Range

Wrapping around on a list when list index is out of range

Use the % operator to produce a modulus:

notes[note % len(notes)]

Demo:

>>> notes = ["a", "a#", "b", "c", "c#", "d", "e", "f", "f#", "g", "g#"]
>>> note = 21
>>> notes[note % len(notes)]
'g#'

or in a loop:

>>> for note in range(22):
... print notes[note % len(notes)],
...
a a# b c c# d e f f# g g# a a# b c c# d e f f# g g#

Wrapping around a list as a slice operation

Rotate left n elements (or right for negative n):

L = L[n:] + L[:n]

Note that collections.deque has support for rotations. It might be better to use that instead of lists.

Wrap list around in Python

Just change:

newIndex = index + key

To:

newIndex = (index + key) % len(charset)

This way, the values will wraparound gracefully

Modulo (%) documentation

How to wrap around to the start/end of a list?

As for wrapping, I would recomend using relative indexing from -1 to +1 and then computing real index using modulo operator (%).

As for making sure you don't count the original element (x, y), you are doing just fine (I would probably use reversed contidion and continue, but it doesn't matter).

I don't quite understand your usage of i, j, k indexes, so I'll just assume that i is index of the species, j, k are indexes into the 2d map called hab which I changed to x_rel, y_rel and x_idx and y_idx to make it more readable. If I'm mistaken, change the code or let me know.

I also took the liberty of doing some minor fixes:

  • introduced N constant representing number of species
  • changed range to xrange (xrange is faster, uses less memory, etc)
  • no need to specify 0 in range (or xrange)
  • instead of X = X + 1 for increasing value, I used += increment operator like this: X += 1

Here is resulting code:

N = len(allspec)
numspec = [0] * N
for i in xrange(N):
for x_rel in xrange(-1, +1):
for y_rel in xrange(-1, +1):
x_idx = (x + xrel) % N
y_idx = (y + yrel) % N
if x_idx != x or y_idx != y:
numspec[hab[x_idx][y_idx]] += 1

Why do I keep getting the error IndexError: list index out of range?

There is no letter after Z (or z). You have to designate the "next" letter, which is usually A (and a). Therefore, [i + self.num] must be [(i + self.num) % len(lowercase)]. The modulo operator wraps the search around.

How to begin from start once index out of range - Python

You can employ operator %:

def getItem(items, index):
return items[index % len(items)]

items = [‘a’, ‘b’, ‘c’, ‘d’]
print(getItem(items, 42))

Output:

c


Related Topics



Leave a reply



Submit