Reputation: 391
I want to store the number of copies of different books in a list as
[10,14,12,16,42,23]
. Here the first element i.e.of index[0]
represents first book has 10 copies, second book (index[1])
has 14 copies like this. But the problem is that I don't know how many kind of books exists, i.e. total number of elements of list is unknown. so that i created an empty list as below:
li = []
After that I run a for loop and in each iteration I want to add and update the list element as follows:
for x in range(5):
li[x] = li[x] + 1
But I am getting the following error:
li[x] = li[x] + 1
IndexError: list index out of range
Because li[x]
has not been assigned to 0
or any value. My question is how can I assign the list with zeroes when number of elements is unknown to me and I am appending the list elements dynamically. Please suggest some approach to achieve my requirement.
Upvotes: 0
Views: 101
Reputation: 639
Try this :
> li = [0] * 5
This is how li
will look like :
> li = [0, 0, 0, 0]
Since you don't know the size so all you can do is to create a list
> li = []
and after some condition keep appending zero
to it
> if condition:
li.append(0)
Upvotes: 0
Reputation: 7268
You can assign 0 as a value in the list. You can try :
>>> for x in range(5):
li.append(0)
>>> print li
[0, 0, 0, 0, 0]
>>> for x in range(5):
li[x] = li[x] + 1
>>> print li
[1, 1, 1, 1, 1]
Upvotes: 1