4

I want to create a 2d array of integer values initially set to 0.

This is how I would think to do it:

grid = [[0] * width] * height

But this just creates each row as a reference to the original, so doing something like

grid[0][1] = 1

will modify all of the grid[n][1] values.

This is my solution:

grid = [[0 for x in range(width)] for y in range(height)]

It feels wrong, is there a better more pythonic way to do this?

EDIT: Bonus question, if the grid size is never going to change and will only contain integers should I use something like a tuple or array.array instead?

Igglyboo
  • 837
  • 8
  • 21

3 Answers3

4

Since numbers are immutable, using * to create a list should be fine. So, the 2D list initialization can be done like this

[[0] * width for y in range(height)]
Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • why not: `[[0]*width]*height` – zeffii Mar 04 '14 at 16:11
  • 1
    @zeffii That will create only one list `[0]*width]` (think of this as `l1`) and create a list with `height` elements in which, all of them are the references to `l1`. So, changing any list will reflect on all the other lists as well. – thefourtheye Mar 04 '14 at 16:14
1

You could use numpy.zeros:

import numpy as np
numpy.zeros(height, width)

If it has to be integer use as option dtype=numpy.int8

theaembee
  • 69
  • 3
  • Yea I've done it with numpy before but I'm trying to avoid external dependencies for my current project. – Igglyboo Mar 04 '14 at 15:42
0

Here is what I used.

def generate_board(n): #Randomly creates a list with n lists in it, and n random numbers
                       #in each mini list
    list = []
    for i in range(0, n):
        list.append([])
        for j in range(0, n):
            list[i].append(random.randint(0, 9))
    return list

def print_board(board):
    n = len(board) - 1
    while n > -1:
        print str(board[n]) + ' = ' + str(n)
        n -= 1
user2874724
  • 97
  • 1
  • 1
  • 8