0

How to use an array index to update a value in array.The compiler keep mention Index Error:list assignment index out of range.

Array Value before change:

[10,0,9,1]

Array value after update:

[9,0,9,1]

x = int(input("Input a number"))

drinkstock = [10,0,9,1]

z=int(drinkstock[x]-1)

for y in drinkstock:

   if drinkstock.index(y)==x:

      drinkstock[y]=z

      print(y)

3
  • 1
    Does this answer your question? Accessing the index in 'for' loops? Commented Aug 12, 2021 at 3:08
  • 1
    It's not clear what you even want to accomplish, tip: don't provide code that depends on user input you can avoid it, especially if you don't provide the input Commented Aug 12, 2021 at 3:09
  • 1
    if you just want to update the array value, why can't you just type drinkstock[x]=z? Commented Aug 12, 2021 at 3:11

2 Answers 2

4

The for y in drinkstock allows you to access each number inside the array drinkstock.

So you would get:

y = 10 #first iteration
y = 0 #second iteration
y = 9 #third iteration
y = 1 #fourth iteration

So then when you do:

drinkstock[y] = z

you are trying to access the 10th index in drinkstock which does not exist.

Instead, you can do:

for i in range(len(drinkstonk)):
    drinkstonk[i] = z

Not sure why you are trying to loop through the entire array though since it looks like you only updated one index value.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, the op is expecting the output to be [9,0,9,1], and so, it should be if i==x: drinkstonk[i] = z inside the for-loop. And the last line should be print(drinkstonk) instead of print(y)
1

cause this list length is 4 is's index just can choose from 0-3.

maybe you can do this

x = int(input("Input a number"))

drinkstock = [10,0,9,1]

if x in drinkstock:
    index = drinkstock.index(x)
    drinkstock[index] = x-1
print(drinkstock)

use list.index() to get x's index in drinkstock to update value

1 Comment

This would work for this particular example but I think it may fail if drinksock happens to have repeated values and another number other than zero is entered as input. For example, if drinkstock happens to be [10,0,10,1] and if the input value happens to be 2 then it would print [9,0,10,1] instead of [10,0,9,1].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.