I've tried this:
x = []
for i in range(5)
x[i] = 0
print(x)
But it gives index out of range exception Why?
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.