0

I am trying to draw lines in Pygame by calling point coordinates from an array index. However, this returns an error:

Traceback (most recent call last): File "C:/Python33/Games/lineTest.py", line 33, in pygame.draw.line(windowSurface,BLACK,(0,0), (0, list[j]), 3) IndexError: list index out of range

Here is my code:

import pygame, sys, random, time
from pygame.locals import *

# sets up pygame
pygame.init()

# sets up the window
windowSurface = pygame.display.set_mode((500, 500), 0, 32)
pygame.display.set_caption('Line Test')

# sets up the colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# draw white background
windowSurface.fill(WHITE)

print('Please enter a number:')
number = input()

# generate random numbers for array
i = 0
list = []
while int(number) > i:
    i = i+1
    x = random.randint(1, 500)
    list.append(x)

# draw lines
j = 0
while int(number) > j:
    j = j+1
    pygame.draw.line(windowSurface,BLACK,(0,0), (0, list[j]), 3)

# Draw the window to the screen
pygame.display.update()

I was wondering if anyone might have a solution for getting past this error?

2
  • 1
    Swap j = j+1 and pygame.draw.line(windowSurface,BLACK,(0,0), (0, list[j]), 3) Also look at docs.python.org/2/tutorial/controlflow.html#the-range-function instead of while loops. Commented Feb 13, 2014 at 21:47
  • Awesome, switching those two lines worked. Thank you! Commented Feb 13, 2014 at 21:56

1 Answer 1

5

You add one to your counters i and j before using them, so you try to access an item one index beyond the end of the list.

Also:

  1. Don't call your own variable list; and
  2. Use for loops, it's what they're there for.

Example:

lst = []
for n in range(number):
     lst.append(...) # or google "python list comprehension"

for item in lst:
    # use item
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for using for loops. No one should have to deal with off-by-one errors in 2014.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.