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

Harish Tech technews.full at gmail.com
Mon Sep 15 14:16:25 CEST 2014


Hi ,

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

exception as it throws when I attempt doing

a[100] = 100


Personal Opinion : Lets see how other languages behave in such a situation
:

1. Ruby :

    > a = [1, 2]

    > a[100] = 100

    > a

 => [1, 2, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, 100]

The way ruby handles this is pretty clear and sounds meaningful (and this
is how I expected to behave and it behaved as per my expectation) at least
to me . Here also it was silently handled but the way it fills non existing
indexes in between with nil sounded meaningful .

2. Java :

When I do such an action in java by using .add(index.value) on may be
arraylist or linkedlist I get java.lang.IndexOutOfBoundException

Here instead of handling it silently it throws an error .


But the python way of handling such a problem by appending to the end
sounds more unexpected to me . This in fact flummoxed me in the beginning
making me think it could be a bug . Then when I raised it in stackoverflow
I got chance to look at source and found that's the way code is written .

Question : 1. Any idea Why it has been designed to silently handle this
instead of at least informing the user with an exception(as in java) or
attaching null values in empty places (as in ruby) ?


Thanks

Harish
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20140915/23dc36df/attachment.html>


More information about the Python-list mailing list