How to create an n*n grid of coordinates?

Viewed 2178

I am having trouble making a 8*8 grid of coordinates in Python 2.7

For the sake of demonstrating, I tried to make a 3x3 grid like this:

grid=[]

for col in xrange(3):
    grid.append([col])
    for row in xrange(3):
        grid[col].append([row])

print grid

I want to have:

grid = [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]

But what I got was:

grid = [[0, [0], [1], [2]], [1, [0], [1], [2]], [2, [0], [1], [2]]]

Any tips?

2 Answers

If you want a list comprehension, this will do it for you.

grid = [[row, col] for row in range(3) for col in range(3)]

Or, if you want to use for loops,

grid = []
for row in range(3):
    for col in range(3):
        grid.append([row, col])

Either of those give this value for grid:

[[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

I know that this is a late answer, but another elegant solution is to use itertools.product:

import itertools

grid = list(itertools.product(xrange(3), xrange(3)))

For Python 3 users, you can replace xrange by range.

You get:

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

Here, coordinates are tuples. IMO, a non-mutable object makes more sense.

Related