Created
March 21, 2012 20:06
-
-
Save adrianp/2152262 to your computer and use it in GitHub Desktop.
How to initialize arrays and copy objects the right way in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This brief script demonstrates a frequent mistake in Python related | |
to the different ways of copying objects. | |
References: | |
1. Personal experience | |
2. http://stackoverflow.com/questions/2196956/add-an-object-to-an-array-python | |
""" | |
import copy # http://docs.python.org/library/copy.html | |
def wrong_way_to_copy(): | |
l = [[]] * 2 # a shallow copy | |
l[0].append(1) | |
print l # we get [[1], [1]] - WRONG! | |
def right_way_to_copy(): | |
l = [copy.copy(x) for x in [[]] * 2] # a deep copy | |
l[0].append(1) | |
print l # we get [[1], []] - RIGHT! | |
wrong_way_to_copy() | |
right_way_to_copy() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment