0

Here is my function's code:

    import random

    def generate(n):

        res = [0]
        x = [0]
        while x == 0:
            x[0] = random.randint(0, 9)
            res = res[0].append(x[0])
        for i in range(1, n - 1):
            x[i] = random.randint(0, 9)
            res[i] = res[i].append(x[i])
        return res

Main program code:

    import number
    n = 20
    f = number.generate(n)
    s = []
    s = number.counter()
    print("{0}" .format(s))

When I run the program I get:

   Traceback (most recent call last):
   f = number.generate(n)
   x[i] = random.randint(0, 9)
   IndexError: list assignment index out of range

Could you tell me how to fix this? Thanks : )

2

4 Answers 4

3

The reason for this error is you are accessing x[0 to n] where you assigned only x[0]. The list have only one index and you are accessing higher indexes. Thats why you are getting list index out of range.

Use this function to generate list of random numbers.

def generate(n):
    return [random.randint(0,9) for i in range(n)]
Sign up to request clarification or add additional context in comments.

Comments

2

You initialise two lists with size 1. When you then try to access the element with index 1 you get an index error.

Try this first:

import random
def generate(n):
    x = [random.randint(1, 9)] + [random.randint(0, 9) for _ in range(n-1)]
    return x

Comments

1

you use append method to add to a list.

x.append (val-to-add-to-list)

for i in range(1, n - 1): 
    x.append (random.randint(0, 9)) 
    res.append(x[i]) 

return res

Comments

1

Your x is a list that has only one element, i.e. 0.

In this line: x[i] = random.randint(0, 9) your first i is equal to 1, thus you are out of range.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.