Skip to content

Instantly share code, notes, and snippets.

@ghsyeung
Created February 25, 2012 02:51
Show Gist options
  • Save ghsyeung/1905475 to your computer and use it in GitHub Desktop.
Save ghsyeung/1905475 to your computer and use it in GitHub Desktop.
Multi-dimensional Array Initilization
k = 1
r = 3
c = 5
# Correct way
A = [[ k ] * c for i in range(r)]
A[0][3] = 0
#>>> A
#[[1, 1, 1, 0, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
# Wrong way - * performs shallow copy, and list are references
A = [[ k ] * c] * 3
A[0][3] = 0
#>>> A
#[[1, 1, 1, 0, 1], [1, 1, 1, 0, 1], [1, 1, 1, 0, 1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment