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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With