rabbit
rabbit

Reputation: 73

Python Error IndexError: list assignment index out of range

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 : )

Upvotes: 0

Views: 1371

Answers (4)

chw21
chw21

Reputation: 8140

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

Upvotes: 2

Ashique PS
Ashique PS

Reputation: 691

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)]

Upvotes: 3

Marcin
Marcin

Reputation: 238139

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.

Upvotes: 1

Tarun Gaba
Tarun Gaba

Reputation: 1113

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

Upvotes: 1

Related Questions