Created
May 11, 2012 13:39
-
-
Save bgbg/2659700 to your computer and use it in GitHub Desktop.
Don't generate list of python mutables using "*" operator
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
>>> 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