More elegant way to initialize list of duplicated items in Python

Posted by Claudiu on Stack Overflow See other posts from Stack Overflow or by Claudiu
Published on 2010-06-09T19:16:41Z Indexed on 2010/06/09 19:22 UTC
Read the original article Hit count: 157

Filed under:
|
|
|

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"?

© Stack Overflow or respective owner

Related posts about python

Related posts about pythonic