string issue

Alex Martelli aleaxit at yahoo.com
Mon Feb 7 14:44:10 EST 2005


Reinhold Birkenfeld <reinhold-birkenfeld-nospam at wolke7.net> wrote:
   ...
> > Using ips[:] to make a copy on the fly is very idiomatic, but I've never
> > liked it, personally.  I see no reason to prefer it to the even shorter
> > and arguably less obscure ips*1, for example.
> 
> "Less obscure"? Either you know the `lst[:]' idiom, or you don't. If you
> do, it's fine, if you don't, you will have to look it up to understand
> its meaning, and that's a good thing.

I disagree.

> Using `lst*1', on the other hand, does not make clear that a copy is
> created. If you don't already know what it does, you may assume that
> `lst' is left alone.

And indeed it is -- whatever object is bound to the name 'lst' is not
modified in the least (neither would it be by slicing lst[:], of
course).  But the RESULT of x*1 is a DISTINCT object from x whenever it
matters -- i.e., whenever x is mutable.  x[:] *MIGHT* not be a distinct,
separate, independent copy if x is, e.g. a Numeric.array:

x = Numeric.arange(7)
y = x[:]
x[3]=23

now y is modified too.  Change the middle statement into 'y = x*1', and
the third statement won't alter y.  So, *WHAT ON EARTH* could possibly
make this weird 'x[:]' form preferable to 'x*1'?!  It's MUCH more
obvious that the second one returns an independent, separate object
initially equal to x -- because it does so in many more cases than those
in which x[:] does it!  I'm not arguing FOR x*1 -- I'm arguing AGAINST
x[:] as being even remotely acceptable.

 
> >  My preference is:
> > 
> >   for ip in list(ips):
> 
> That is the most intriguing variant, of course.

It's very down to earth because the result is obviously a list, whatever
'ips' might turn out to be -- no mystery there, and thus, no intrigue.
Maybe we should have a simpler way to specify ``an iterator that is
INDEPENDENT from any possible changes in the iterable we're passing'',
for this specific use case -- but we don't, and I don't think that
copy.copy(ips) is a substantial improvement (it would fail when ips is a
file, or a generator-iterator, or many other kinds of iterators, for
example).  list(ips) may do more work than necessary (e.g., if ips were
a tuple) but at least its semantics are quite plain and obvious.


Alex



More information about the Python-list mailing list