Skip to content

Instantly share code, notes, and snippets.

@adrianp
Created March 21, 2012 20:06
Show Gist options
  • Save adrianp/2152262 to your computer and use it in GitHub Desktop.
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 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