Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring and populating 2D array in python

Tags:

python

arrays

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?

like image 859
Dangila Avatar asked Dec 11 '22 11:12

Dangila


2 Answers

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.

like image 92
Shayne Avatar answered Dec 23 '22 17:12

Shayne


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.

like image 25
Itay Karo Avatar answered Dec 23 '22 16:12

Itay Karo