<div dir="ltr"><div class="gmail_quote"><div dir="ltr">On Fri, Mar 31, 2017 at 2:49 AM Suresh V. via Python-ideas <<a href="mailto:python-ideas@python.org">python-ideas@python.org</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">On Thursday 30 March 2017 02:48 PM, Markus Meskanen wrote:<br class="gmail_msg">
> Hi Pythonistas,<br class="gmail_msg">
><br class="gmail_msg">
> yet again today I ended up writing:<br class="gmail_msg">
><br class="gmail_msg">
> d = [[0] * 5 for _ in range(10)]<br class="gmail_msg">
><br class="gmail_msg">
> And wondered, why don't we have a way to repeat other than looping over<br class="gmail_msg">
> range() and using a dummy variable? This seems like a rather common<br class="gmail_msg">
> thing to do, and while the benefit doesn't seem much, something like<br class="gmail_msg">
> this would be much prettier and more pythonic than using underscore<br class="gmail_msg">
> variable:<br class="gmail_msg">
><br class="gmail_msg">
> d = [[0] * 5 repeat_for 10]<br class="gmail_msg">
<br class="gmail_msg">
Why not:<br class="gmail_msg">
<br class="gmail_msg">
d = [[0] * 5 ] * 10<br class="gmail_msg"></blockquote><div><br></div><div>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.<br></div></div></div>