Created
February 25, 2012 02:51
-
-
Save ghsyeung/1905475 to your computer and use it in GitHub Desktop.
Multi-dimensional Array Initilization
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
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