Reputation: 37
Consider:
def generate_distribution(size, distribution_positive, distribution_negative):
x = int(distribution_negative * 100)
y = int(distribution_positive * 100)
new_list = []
i = 0
for i in range(size):
if i < x: # 0-24
new_list[i-1].append(-1)
elif i >= x and i < (x + y):
new_list[i-1].append(1)
else:
new_list[i-1].append(0)
return new_list
I am a beginner trying to learn Python. Why is this is out of range?
distribution_negative and distribution_positive are meant to be given as decimals, hence the multiplication by 100 above.
Upvotes: 0
Views: 63
Reputation: 1332
Your variable named new_list
starts as empty, so on your first iteration you're trying to access the location of new_list[i-1]
which means new_list[-1]
which is invalid since the list is currently empty. Before accessing an item in the list, you need to make sure that the list is not empty.
Also, after making sure that the list is not empty, make sure you're not accessing a negative index location (also invalid, unless you take part of the list, a.k.a new_list[2: -1]
which will give you the list from index 2 till 1 before the last one).
Upvotes: 3