Skip to content

Instantly share code, notes, and snippets.

@bgbg
Created May 11, 2012 13:39
Show Gist options
  • Save bgbg/2659700 to your computer and use it in GitHub Desktop.
Save bgbg/2659700 to your computer and use it in GitHub Desktop.
Don't generate list of python mutables using "*" operator
>>> m = [[]] * 10
>>> m
[[], [], [], [], [], [], [], [], [], []]
>>> #everything seems to be OK
...
>>> m[0].append(10)
>>> m
[[10], [10], [10], [10], [10], [10], [10], [10], [10], [10]]
>>> #shit!
...
>>> m = [set()] * 10
>>> m
[set([]), set([]), set([]), set([]), set([]), set([]), set([]), set([]), set([]), set([])]
>>> m[0].add(10)
>>> m
[set([10]), set([10]), set([10]), set([10]), set([10]), set([10]), set([10]), set([10]), set([10]), set([10])]
>>> #you already knew that
...
>>>
>>> #That's how we need to to this:
...
>>> m = [[] for i in range(10)]
>>> m
[[], [], [], [], [], [], [], [], [], []]
>>> m[0].append(10)
>>> m
[[10], [], [], [], [], [], [], [], [], []]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment