Why is this out of range?

Question:

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.

Asked By: Osmani

||

Answers:

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)

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.