0
class WorldMap (object):
def __init__ (self, width, height):
    self.width = width
    self.height = height
    world = []
    for i in range(self.width):
        world.append(None)
        for j in range(self.height): 
                                world[i].append(None)


class WorldMap(object):
def __init__(self, width, height):
    self.width = width
    self.height = height
    self.map = [[None for x in range(self.width)] for y in range(self.height)]
  1. The second successfully creates a grid. I don't understand why the first code doesn't work.
  2. to create an empty grid with lists, I tried using None and '' in the first code, but neither work. Why are both '' and None as used in the first code not correct ?
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user26809
  • 27
  • 1
  • 5
  • 1
    `numpy.zeros(width*height).reshape((width,height))` is your best, fastest, and simplest way of doing it ... at least imho ... plus familiarizing yourself with numpy arrays early on will help you tons later – Joran Beasley Jan 14 '14 at 16:55

4 Answers4

3

In your first code, the outer i loop:

world = []
for i in range(self.width):
    world.append(None)

creates a list of None:

world == [None, None, None, ...]

therefore in the inner j loop, when you call

world[i].append(None)

you are trying to call:

None.append(None)

and you can't append to None! The outer loop should have been:

world.append([]) # an empty list

Then the inner loop will work correctly with whatever (None, "", etc.) you want to put in those lists.

It is worth noting that the second version is much neater than the first, with (obviously!) less potential for error. However, a small improvement (as you never use x or y):

self.map = [[None for _ in range(width)] for _ in range(height)]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
0

In your first code in the first loop you should be appending an empty list rather than None. Also the second version is way better.

El Bert
  • 2,958
  • 1
  • 28
  • 36
0

Let's assume the grid size will be:

size = 4

Now, we're making an empty grid:

grid = []

for y in range(size): grid = grid + [[]] for x in range(size): grid[y] = grid[y] + [0]

When you now call your grid you should get: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Jowita Emberton
  • 166
  • 2
  • 3
-1

What about this?

grid = [[0] * 20] * 20

omkin
  • 1
  • 1
    This will create 20 copies of the same list, such that changing grid[0] will also change grid[1], grid[2], etc. See https://stackoverflow.com/a/240205. – K-- Oct 11 '19 at 14:37