newbie while loop error: IndexError: list assignment index out of range - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: newbie while loop error: IndexError: list assignment index out of range (/thread-2652.html) |
newbie while loop error: IndexError: list assignment index out of range - msa969 - Mar-31-2017 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)
RE: newbie while loop error: IndexError: list assignment index out of range - wavic - Mar-31-2017 numbers = list(range(1, 31)) RE: newbie while loop error: IndexError: list assignment index out of range - zivoni - Mar-31-2017 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 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] RE: newbie while loop error: IndexError: list assignment index out of range - msa969 - Mar-31-2017 thanks |