0

I'm used to C programming where if you wanted to allocate space 2d array you just declare it as

int a[20][20];

I'm not too used to Python programming yet (I'm still in the C mindstate)

I want to declare a list of lists in this section of code and initalize each element to none.

class World:
    def __init__(self):
        grid = [[none]*20]*20

For some reason it doesn't look right to me. Can someone help me out?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
ShadyBears
  • 3,955
  • 13
  • 44
  • 66

1 Answers1

4

grid = [[None]*20]*20 will give you a list of 20 sublists, each of which contains 20None`s. However, all the sublists will be references to the same list in memory, so changing one will affect them all.

You're better off doing something like this:

grid = [[None for _ in xrange(20)] for __ in xrange(20)]

This will give you 20 distinct sublists, each of which contains 20 Nones

Further reading

Community
  • 1
  • 1
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241