I'm trying to add elements into my list using the range function but it doesn't seem to work

Issue

numberinput = []
for x in range(1, 11):
  arrayinput = input("Type the number you want to add to the array")
  numberinput[x] = arrayinput
print(numberinput)

I’ve created an empty list and what im trying to is, im trying to increment x to add 10 numbers into the list but it just displays

IndexError: list assignment index out of range

Solution

In Python lists, you can only refer to elements that exist. Do it like this:

numberinput = []
for x in range(10):
  arrayinput = input("Type the number you want to add to the array")
  numberinput.append( arrayinput )
print(numberinput)

Note that numbering starts at 0, so this will ask for 10 numbers. Also note they will be stored as strings.

Answered By – Tim Roberts

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published