Created
July 23, 2013 15:20
-
-
Save sergray/6063222 to your computer and use it in GitHub Desktop.
Python list of lists gotcha, showing that it's not a good idea to create 2d array with multiplication of lists. Inner lists turns out to be the references to the same object.
This file contains hidden or 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
In [1]: list_of_lists = [['#'] * 4] * 4 | |
In [2]: list_of_lists | |
Out[2]: | |
[['#', '#', '#', '#'], | |
['#', '#', '#', '#'], | |
['#', '#', '#', '#'], | |
['#', '#', '#', '#']] | |
In [3]: map(id, list_of_lists) | |
Out[3]: [4333427312, 4333427312, 4333427312, 4333427312] | |
In [4]: list_of_lists[1][1] = '1' | |
In [5]: list_of_lists | |
Out[5]: | |
[['#', '1', '#', '#'], | |
['#', '1', '#', '#'], | |
['#', '1', '#', '#'], | |
['#', '1', '#', '#']] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
the correct creation of the list of lists is