4

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
  • 5
  • 17
Dangila
  • 1,344
  • 3
  • 13
  • 23
  • 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

5 Answers5

4

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,585
  • 1
  • 15
  • 18
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,370
  • 4
  • 38
  • 56
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,815
  • 2
  • 47
  • 71
2

Try this:

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

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

This will give you a 2D dictionary you can access like val=status[0,3]

Shayne
  • 1,585
  • 1
  • 15
  • 18
  • I should note, in the 5 years since I've posted this, I'e come to the conclusion using dicts for arrays isnt always the most performant way of doing things. – Shayne Dec 14 '17 at 21:14
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.
  • 368
  • 1
  • 11