Skip to content
Advertisement

Select a random element from a 2d array list in python

I currently have a 2d array generated by this code:

for y in range(width):
    self.grid.append([])
    for x in range(width):
        self.grid[y].append(Cell(x, y))

If I want to select a random cell, how would I go about it? random.choice doesn’t seem to be working.

Advertisement

Answer

You could do something like

yCoord = random.randrange(width)
xCoord = random.randrange(width)
randomCell = self.grid[yCoord][xCoord]

If you do want to use random.choice, you’ll have to use it twice, as the first call will return an array of Cells, then the second one will return a cell element.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement