usman imtiaz
usman imtiaz

Reputation: 714

Trying to insert value in list from user in for loop raises IndexError

How many values he/she want to add and then he insert values using loop.

I use this loop for sorting:

value = int(input("how many number u want to add"))

arr = [value]
for n in range(0, value):
    arr[value] = input("Enter value")

for n in range(0, value):
    print(arr[value])

It shows the error:

  arr[value] = input("Enter value")
IndexError: list assignment index out of range

Upvotes: 3

Views: 6119

Answers (2)

Djaouad
Djaouad

Reputation: 22766

If you think that doing arr = [value] will create an array of length value, then you're wrong, it just creates a list that has one element, value, if you want to create a list that has value length, you can use list multiplication:

value = int(input("how many number u want to add"))

arr = [0] * value

for n in range(value):
    arr[n] = input("Enter value")

for n in arr:  #  iterate over the elements directly, rather than indexing
    print(n)

And another way is to use list.append to dynamically add elements to a list:

value = int(input("how many number u want to add"))

arr = []

for n in range(value):
    arr.append(input("Enter value"))

for n in arr:
    print(n)

Upvotes: 4

SyntaxVoid
SyntaxVoid

Reputation: 2623

  1. I don't think arr = [value] is what you meant to write. Did you mean to make an empty array/list with that many values? If so, you can do that by arr = [0]*value which will fill your array with zeros and will be 'value' elements long. Creating the list to the exact size you want on creation is a good idea to help speed up your code a little bit (relative to creating an empty list and appending every value). In this tiny example, it will not be noticed, but larger scale projects can benefit from this kind of thing.

  2. In your for loop, the n variable is your index into the array, so change arr[value] = input("Enter value") to arr[n] = input("Enter value"). Side note: Any values added this way will be strings and not integers.

  3. Same as (2) for your second for loop, print(arr[value]) should be print(arr[n]).

Upvotes: 2

Related Questions