Skip to content

Instantly share code, notes, and snippets.

@sergray
Created July 23, 2013 15:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergray/6063222 to your computer and use it in GitHub Desktop.
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.
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', '#', '#']]
@sergray
Copy link
Author

sergray commented Jul 23, 2013

the correct creation of the list of lists is

list_of_lists = [['#'] * 4 for i in range(4)]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment