Bottom Page

Thread Rating:
  • 3 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 newbie while loop error: IndexError: list assignment index out of range
#1
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
Quote
#2
numbers = list(range(1, 31))
nilamo likes this post
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Quote
#3
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]
nilamo likes this post
Quote
#4
thanks
nilamo likes this post
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  item = index position - list of list RavCOder 9 131 Dec-02-2019, 05:24 PM
Last Post: ThomasL
  Is 2 a prime number? for loop & range fuction in python docs says yes, mine says no. allusernametaken 4 122 Nov-17-2019, 02:56 AM
Last Post: allusernametaken
  IndexError: List index out of range issue Adem 1 282 Nov-01-2019, 10:47 PM
Last Post: ichabod801
  ValueError: Index contains duplicate entries, cannot reshape” error when I try to use Smiling29 11 351 Oct-26-2019, 09:52 PM
Last Post: Smiling29
  IndexError: list index out of range bug? CaptainCsaba 4 277 Oct-18-2019, 12:38 PM
Last Post: CaptainCsaba
  loop through range until reach size and exclude specific symbol pino88 3 163 Sep-23-2019, 02:32 AM
Last Post: perfringo
  Newbie error dezed 4 143 Sep-22-2019, 03:01 PM
Last Post: dezed
  returns index of list if contains a word zarize 0 141 Sep-09-2019, 09:29 AM
Last Post: zarize
  MAWS.py PRGM:IndexError: list index out of range bcramer 0 148 Aug-28-2019, 04:45 PM
Last Post: bcramer
  Select a part of an element of a list with Index BollerwagenIng 0 297 Aug-09-2019, 09:27 AM
Last Post: BollerwagenIng

Forum Jump:


Users browsing this thread: 1 Guest(s)