1

I was wondering:

def get_empty_cell():
    return {'p': [[], []], 'h': {}, 'b': []}

def create_new_board(old_board):
    height = len(old_board) + 4
    width = len(old_board[0]) + 4
    self.board = [None] * height
    for i in range(0, height):
        self.board[i] = [None] * width
        for j in range(0, width):
            # (!) deepcopy() 
            self.board[i][j] = copy.deepcopy(self.get_empty_cell())

I'm using deepcopy because I've had many situations where different variables access the same content. But when Python returns "new" dictionaries like in my code, do I need to use copy.deepcopy if I want different cells or is it like JavaScript?

(and off topic: I'm sure my code could be optimized "the Python way"...)

ozgur
  • 41,172
  • 16
  • 73
  • 106
Olivier Pons
  • 13,972
  • 24
  • 98
  • 190
  • `get_empty_cell()` returns a new dictionary every time it is called. So you don't need copy.deepcopy there. I am pretty sure this behavior is common almost in all programming languages. – ozgur Apr 27 '16 at 06:15

2 Answers2

2

get_empty_cell() returns a new dictionary from a literal each time. There's no need to copy it again.

TigerhawkT3
  • 44,764
  • 6
  • 48
  • 82
  • +1 for mentioning that the returned dictionary is defined using literals. If that were not the case there could be several references to the same object in the board even if each cell is a different dictionary. – Stop harming Monica Apr 27 '16 at 07:13
2

As in the other answer, you don't need to make a copy because get_empty_cell() returns a new dict each time you call it.

And yes! you can optimize your code like this:

self.board = [[self.get_empty_cell() for j in range(width)] for i in range(height)]
AKS
  • 15,194
  • 2
  • 32
  • 47
  • AKS strikes again **`;^)`** But I get a warning in Pycharm "j" and "i" are not used. Is there a way to write something like (didnt try) `[[self.get_empty_cell()*width]*height]` – Olivier Pons Apr 27 '16 at 06:36
  • Thanks @OlivierPons! In your last question also you were struggling with this type of optimization. I would suggest that you read about [list comprehensions](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) for better understanding. – AKS Apr 27 '16 at 06:39
  • I think you can write something like this: `[[self.get_empty_cell()] * width] * height` but I wouldn't advise because then the same copy of dict will be distributed to each cell and if you modify one cell all will be modified. – AKS Apr 27 '16 at 06:41
  • Ok then. Thank you again. – Olivier Pons Apr 27 '16 at 06:46
  • Have a look at [this comment](http://stackoverflow.com/questions/21867749/is-local-variable-necessary-in-python-comprehensions#comment48378162_21867767) if you don't want to get these warnings. – AKS Apr 27 '16 at 06:48