Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #77928

Re: List insert at index that is well out of range - behaves like append that too SILENTLY

Date 2014-09-16 13:04 +0100
From MRAB <python@mrabarnett.plus.com>
Subject Re: List insert at index that is well out of range - behaves like append that too SILENTLY
References <CACC6tEh0b-iR3ChEsYZftxjSJktzqbknqAeTdpxyHCdS7YRHiQ@mail.gmail.com> <8738bsds44.fsf@handshake.de>
Newsgroups comp.lang.python
Message-ID <mailman.14053.1410869105.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 2014-09-16 06:58, dieter wrote:
> Harish Tech <technews.full@gmail.com> writes:
>
>> Let me demonstrate the problem I encountered :
>>
>> I had a list
>>
>>  a = [1, 2, 3]
>>
>> when I did
>>
>> a.insert(100, 100)
>>
>> [1, 2, 3, 100]
>>
>> as list was originally of size 4 and I was trying to insert value at index
>> 100 , it behaved like append instead of throwing any errors as I was trying
>> to insert in an index that did not even existed .
>>
>>
>> Should it not throw
>>
>> IndexError: list assignment index out of range
>
> At least the documentation states that what you observe is the intended
> behaviour.
>
> According to the documentation, "a.insert(i, x)" is
> equivalent to "a[i:i] = x" (i.e. a slice assignment) and
> if in a slice "a[i:j]" "i" or "j" are larger then "len(a)",
> then it is replaced by "len(a)".
>
> If this is not what you want, derive your own list type
> and override its "insert" method.
>
It's nice to be able to say a.insert(p, x) even when p == len(a)
instead of having a special case:

if p == len(a):
     a.append(x)
else:
     a.insert(p, x)

Of course, what to do when p > len(a) is another matter.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: List insert at index that is well out of range - behaves like append that too SILENTLY MRAB <python@mrabarnett.plus.com> - 2014-09-16 13:04 +0100

csiph-web