Is python deepcopy more efficient than custom code, or less efficient/predictable?

Viewed 1141

I have a dict where the values are non-nested lists (specifically, the keys are ints and the values are lists of ints). I'd like to make a deep copy of it so that I don't modify the lists in the original dict.

I know I can use

copied = copy.deepcopy(original)

However since I know the form of the data structure I can also use something like

copied = {key:valuelist[:] for (key,valuelist) in original.iteritems()}

Is one of these solutions better? More efficient? Less likely to lead to nasty surprises?

I have been told that deepcopy() comes with some gotchas but I don't really understand what. I would also like to understand whether using deepcopy() is less efficient than my code (maybe because it's a more general solution?) or more efficient (maybe it's optimised at a lower level?).

3 Answers
Related