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?

lambda
  • 407
  • 1
  • 5
  • 18
Dangila
  • 1,434
  • 3
  • 14
  • 25
  • possible duplicate of [How to define Two-dimensional array in python](http://stackoverflow.com/questions/6667201/how-to-define-two-dimensional-array-in-python) – gst Sep 27 '13 at 06:39

4 Answers4

5

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.

Shayne
  • 1,571
  • 1
  • 16
  • 20
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.

Itay Karo
  • 17,924
  • 4
  • 40
  • 58
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())
justhalf
  • 8,960
  • 3
  • 47
  • 74
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]])
Pierre H.
  • 388
  • 1
  • 11