Adding item in front of a list
Alex Martelli
aleaxit at yahoo.com
Thu Apr 10 03:25:46 EDT 2003
Tim Peters wrote:
> [Andrew Koenig, starting with l=[2, 3, 4]]
>> ...
>> I would have thought that after l.insert(-1, 1), l would be
>> [2, 3, 1, 4], but it doesn't work that way.
>
> Alas, list.insert() existed before sequence indices were generalized to
> give
> a "count from the right end" meaning to negative index values. When the
> generalization happened, it appears that list.insert() was just
> overlooked.
>
> I'd like to change this. If I did, how loudly would people scream?
If you presented it as a *bug fix* I wouldn't scream -- I'd PURR...!!!
Consider:
>>> def ins1(al, where, what):
... al.insert(where, what)
...
>>> def ins2(al, where, what):
... al[where:where] = [what]
...
are these two functions equivalent? It sure seems so...:
>>> a=list('lopkan'); ins1(a, 2, 'i'); print a
['l', 'o', 'i', 'p', 'k', 'a', 'n']
>>> a=list('lopkan'); ins2(a, 2, 'i'); print a
['l', 'o', 'i', 'p', 'k', 'a', 'n']
BUT the bug breaks the equivalence when where<0...!
>>> a=list('lopkan'); ins2(a, -2, 'i'); print a
['l', 'o', 'p', 'k', 'i', 'a', 'n']
>>> a=list('lopkan'); ins1(a, -2, 'i'); print a
['i', 'l', 'o', 'p', 'k', 'a', 'n']
>>>
Yeah, I know, the docs now carefully guard this assertion of equivalence
with an "if i >= 0" and just as carefully specify that if i < 0 then the
item being "inserted" is actually prepended to the sequence. So I'd say
there's a bug in the DOCS, too...;-)
> Guido says he also wishes list.insert() had been defined with the
> arguments in the opposite order, so that list.insert(object) could have a
> natural
> default index argument of 0. I'd like to change that too, but it's
> clearly too late for that one.
Yep. This has to go into a list of "tiny warts that will never be
fixed because we DO need backwards compatibility, sigh".
Alex
More information about the Python-list
mailing list