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?

0

3 Answers 3

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)]
Sign up to request clarification or add additional context in comments.

2 Comments

why not: [[0]*width]*height
@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.
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

1 Comment

Yea I've done it with numpy before but I'm trying to avoid external dependencies for my current project.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.