More elegant way to initialize list of duplicated items in Python
- by Claudiu
If I want a list initialized to 5 zeroes, that's very nice and easy:
[0] * 5
However if I change my code to put a more complicated data structure, like a list of zeroes:
[[0]] * 5
will not work as intended, since it'll be 10 copies of the same list. I have to do:
[[0] for i in xrange(5)]
that feels bulky and uses a variable so sometimes I even do:
[[0] for _ in " "]
But then if i want a list of lists of zeros it gets uglier:
[[[0] for _ in " "] for _ in " "]
all this instead of what I want to do:
[[[0]]*5]*5
Has anyone found an elegant way to deal with this "problem"?