
On Fri, Mar 31, 2017 at 2:49 AM Suresh V. via Python-ideas < python-ideas@python.org> wrote:
On Thursday 30 March 2017 02:48 PM, Markus Meskanen wrote:
Hi Pythonistas,
yet again today I ended up writing:
d = [[0] * 5 for _ in range(10)]
And wondered, why don't we have a way to repeat other than looping over range() and using a dummy variable? This seems like a rather common thing to do, and while the benefit doesn't seem much, something like this would be much prettier and more pythonic than using underscore variable:
d = [[0] * 5 repeat_for 10]
Why not:
d = [[0] * 5 ] * 10
If you had read the thread before replying, you would have seen that several people have suggested this, and several others have pointed out why it won't work: because that creates a list of 10 references to the SAME five-element list, meaning that mutating d[0] also affects d[1] through d[9] (since each is the same list). The comprehension is necessary to ensure that each element of d is a distinct list.