pythonlistnegative-number

Python, negative values aren't out of range in list


class world:
    def __init__(self, screen_size):
        self.map = [[0 for col in range(500)] for row in range(500)]
        self.generate()

    def generate(self):
        for x in range(0, len(self.map[0])):
            for y in range(0, len(self.map)):
                kind = random.randint(0, 100)
                if kind <= 80:
                    self.map[x][y] = (random.randint(0, 255),random.randint(0, 255),random.randint(0, 255))
                else:
                    self.map[x][y] = (random.randint(0, 255),random.randint(0, 255),random.randint(0, 255))
        print self.map[50][50], self.map[-50][-50]
printing => (87, 92, 0) (31, 185, 156)

How is this possible that negative values aren't out of range? It should throw IndexError.


Solution

  • Using negative numbers starts at the back of the list and counts down, that's why they still work.