5

I want to declare and populate a 2d array in python as follow:

def randomNo():
    rn = randint(0, 4)
    return rn

def populateStatus():
    status = []
    status.append([])
    for x in range (0,4):
        for y in range (0,4):
            status[x].append(randomNo())

But I always get IndexError: list index out of range exception. Any ideas?

1

4 Answers 4

7

More "modern python" way of doing things.

[[ randint(0,4) for x in range(0,4)] for y in range(0,4)]

Its simply a pair of nested list comprehensions.

Sign up to request clarification or add additional context in comments.

Comments

3

The only time when you add 'rows' to the status array is before the outer for loop.
So - status[0] exists but status[1] does not.
you need to move status.append([]) to be inside the outer for loop and then it will create a new 'row' before you try to populate it.

Comments

3

You haven't increase the number of rows in status for every value of x

for x in range(0,4):
    status.append([])
    for y in range(0,4):
        status[x].append(randomNo())

Comments

1

If you're question is about generating an array of random integers, the numpy module can be useful:

import numpy as np
np.random.randint(0,4, size=(4,4))

This yields directly

array([[3, 0, 1, 1],
       [0, 1, 1, 2],
       [2, 0, 3, 2],
       [0, 1, 2, 2]])

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.