[Python-ideas] Way to repeat other than "for _ in range(x)"

Steven D'Aprano steve at pearwood.info
Fri Mar 31 00:36:42 EDT 2017


On Thu, Mar 30, 2017 at 04:23:05PM +0200, Pavol Lisy wrote:
> On 3/30/17, Nick Coghlan <ncoghlan at gmail.com> wrote:
> > On 30 March 2017 at 19:18, Markus Meskanen <markusmeskanen at gmail.com>
> > wrote:
> >> Hi Pythonistas,
> >>
> >> yet again today I ended up writing:
> >>
> >> d = [[0] * 5 for _ in range(10)]
> 
>     d = [[0]*5]*10  # what about this?

That doesn't do what you want.

It's actually a common "gotcha", since it makes ten repetitions of the 
same five element list, not ten *copies*.

py> d = [[0]*5]*10
py> d[0][0] = 9999
py> print(d)
[[9999, 0, 0, 0, 0], [9999, 0, 0, 0, 0], [9999, 0, 0, 0, 0], [9999, 0, 
0, 0, 0], [9999, 0, 0, 0, 0], [9999, 0, 0, 0, 0], [9999, 0, 0, 0, 0], 
[9999, 0, 0, 0, 0], [9999, 0, 0, 0, 0], [9999, 0, 0, 0, 0]]


A slightly unfortunate conflict between desires: on the one hand, we 
definitely don't want * making copies of its arguments; on the other 
hand, that makes it less useful for initialising multi-dimensional 
(nested) lists.

But then, nested lists ought to be rare. "Flat is better than nested."


> Simplified repeating could be probably useful in interactive mode.

I'm sorry, did you just suggest that language features should behave 
differently in interactive mode than non-interactive mode?

If so, that's a TERRIBLE idea. The point of interactive mode is to try 
out syntax and code and see what it does, before using it in non- 
interactive scripts. If things behave differently, people will be left 
confused why the *exact same line of code* works differently in a script 
and when they try it interactively.

It is bad enough that the interactive interpreter includes a handful of 
features that make it different from non-interactive. I've been caught 
out repeatedly by the "last evaluated result" variable _ changing when 
the destructor method __del__ runs. That's another unavoidable case: 
adding extra, necessary functionality to the interactive interpreter, 
namely the ability to access the last evaluated result, neccessarily 
holds onto a reference to that last result. But that's easy enough to 
reason about, once you remember what's going on.

But changing the behaviour of the language itself is just a bad idea. 


-- 
Steve


More information about the Python-ideas mailing list