Last active
January 6, 2016 17:29
-
-
Save gregroberts/91477b04bbf5dc8229ad to your computer and use it in GitHub Desktop.
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
#odd quirk found on Python | |
#say you have a list of values, and you want a dict with keys for each item, and each value an empty array. | |
#I found myself in this situation, and I decided to do it like this: | |
l = ['a','b','c'] | |
gg = dict(zip(l,[[]]*3)) | |
gg | |
#however, when you try and put a value into one of those arrays: | |
gg['a'].append(1) | |
gg | |
#1: {'a': [1], 'b': [1], 'c': [1]} | |
#the value is added to all 3! | |
gg = [[]]*5 | |
gg | |
gg[0].append(1) | |
gg | |
#5: [[1], [1], [1], [1], [1]] | |
#the bastard | |
#I've now settled on the slightly less terse | |
gg = {i:[] for i in l} | |
#and now I don't know why in fuck I didn't do that in the first place | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment