Python Forum
newbie while loop error: IndexError: list assignment index out of range
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
Reply
#2
numbers = list(range(1, 31))
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#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]
Reply
#4
thanks
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How is pandas modifying all rows in an assignment - python-newbie question markm74 1 652 Nov-28-2023, 10:36 PM
Last Post: deanhystad
  IndexError: index 10 is out of bounds for axis 0 with size 10 Mehboob 11 1,948 Sep-14-2023, 06:54 AM
Last Post: Mehboob
  pyscript index error while calling input from html form pyscript_dude 2 938 May-21-2023, 08:17 AM
Last Post: snippsat
  Index error help MRsquared 1 738 May-15-2023, 03:28 PM
Last Post: buran
  [SOLVED] [loop] Exclude ranges in… range? Winfried 2 1,366 May-14-2023, 04:29 PM
Last Post: Winfried
Thumbs Down I hate "List index out of range" Melen 20 3,154 May-14-2023, 06:43 AM
Last Post: deanhystad
Exclamation IndexError: Replacement index 2 out of range for positional args tuple - help? MrKnd94 2 5,956 Oct-14-2022, 09:57 PM
Last Post: MrKnd94
  Replace for loop to search index position illmattic 5 1,225 Sep-03-2022, 04:04 PM
Last Post: illmattic
  IndexError: list index out of range dolac 4 1,843 Jul-25-2022, 03:42 PM
Last Post: deanhystad
  I'm getting a String index out of range error debian77 7 2,277 Jun-26-2022, 09:50 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020