Python Forum

Full Version: newbie while loop error: IndexError: list assignment index out of range
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to create a list called numbers that contains all the integers from 1 to 30 

numbers = []
i = 1
while(i < 30):
    numbers[i] = i +1 

print(numbers)
Error:
   numbers[i] = i +1 IndexError: list assignment index out of range
numbers = list(range(1, 31))
You cant assign value to a list "position" if it doesnt exist yet. You can modify your code to use append (and to increase i variable):
numbers = []
i = 1
while (i <= 30):    
  numbers.append(i)
  i += 1
print(numbers)
gives
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
but much better is to use built-in range():
>>> list(range(1,31))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
thanks