0

I'm trying to make a wordsearch for a school project and have hit a snag. I am using a class with functions for the board. Here is my code:

class Board:
    def __init__(self,size=20):
        self.board = [['']*size]*size
        self.board[0][0] = 'A'
        self.words = ['lorem', 'ipsum', 'dolor', 'sit', 'amet',\
                      'consectetur', 'adipiscing', 'elit', 'quisque',\
                      'in', 'augue', 'sit', 'amet', 'est', 'ullamcorper',\
                      'bibendum', 'sed', 'at', 'arcu', 'nullam']
        self.clues = self.words

board = Board()
print ''.join(board.board[0])
print ''.join(board.board[1])

Instead of printing out the expected ('' = nothing)

A
''

It prints out

A
A

What am I doing wrong?

DoctorSelar
  • 486
  • 2
  • 7
  • 16
  • 1
    This is a duplicate but I can never remember the question title – jamylak May 22 '13 at 12:27
  • “Note also that the copies are shallow; nested structures are not copied. This often haunts new Python programmers” http://docs.python.org/3.3/library/stdtypes.html#common-sequence-operations – Ry- May 22 '13 at 12:32

1 Answers1

3

This creates a list of references to the same list

self.board = [['']*size]*size

You need to make a new list for each entry like this

self.board = [['']*size for x in range(size)]

It's only safe to multiply immutable objects across a list like this. Eg

['']*size
[0]*size

Since you are forced to replace the entries rather than modify them

John La Rooy
  • 295,403
  • 53
  • 369
  • 502