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)

Yun Song
  • 39
  • 4
  • 1
    Does this answer your question? [Accessing the index in 'for' loops?](https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops) – enzo Aug 12 '21 at 03: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*** – juanpa.arrivillaga Aug 12 '21 at 03:09
  • 1
    if you just want to update the array value, why can't you just type `drinkstock[x]=z`? – Suneesh Jacob Aug 12 '21 at 03:11

2 Answers2

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.

Yi Yang
  • 78
  • 6
  • 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)` – Suneesh Jacob Aug 12 '21 at 03:18
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

iamjing66
  • 61
  • 6
  • 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]`. – Suneesh Jacob Aug 12 '21 at 03:23