0

I've tried this:

x = []
for i in range(5)
    x[i] = 0
print(x)

But it gives index out of range exception Why?

Yousef
  • 11
  • 4
  • x is python list and not array. If you want to append the values to x, you can x.append(i) , or you can also initialize the list with fixed size and use the assignment as mentioned https://stackoverflow.com/questions/10712002/create-an-empty-list-in-python-with-certain-size – Chota Bheem Jan 28 '21 at 04:44
  • @Yousef if solved question please marked as an answer will help me and others too in future – l.b.vasoya Jan 29 '21 at 09:34

3 Answers3

1

Because there is not any value in list that's why In this case you have to use append

like

x = []
for i in range(5)
    x.append(0) #x[i] = 0 
print(x)

remove this line x[i] = 0 and put x.append(0)

l.b.vasoya
  • 1,188
  • 8
  • 23
0

You're getting a index out of range exception because there is nothing in your list. If you want to loop 5 times and set x[i] = 0 there has to be a x[i] first.

Merp
  • 118
  • 1
  • 10
0

You created an empty list x = [] (not an array) and in a line x[i] = 0 where you are trying to assign element 0 with index=0 which does not exist at the time of initialization, here in your case it will be the first iteration of for loop with i=0.

Here is the example :

>>> x = []
>>> x[0] = 0
 Traceback (most recent call last):
 File "<pyshell#8>", line 1, in <module>
    x[0] = 0
 IndexError: list assignment index out of range

It will not allow you to assign element with index to an empty list.

Girish
  • 366
  • 3
  • 15