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
Question :
1. Any idea Why has it been designed to silently handle this instead of informing the user with an exception ?
Personal Opinion :
Lets see how other languages behave in such a situation :
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 at least to me .
Java :
In java the method .add(index, value) if applied with index that is out of range(on arraylist , linkedlist for example) will throw
java.lang.IndexOutOfBoundsException .
So what I felt was either it should throw exception(as java does) or insert null in the range in between (as ruby handles it ).
But the silent way of handling in python is just flummoxing .
UPDATE (16 Sep 2014 IST 8:30 AM) :
As suggested by one of the answerers I posted this question in python-dev and I got a response . It can be seen in this python dev mailing list thread . If you find that the thread link has changed, you can find the answer by doing a google search for the title of question appended at the beginning with python dev.
See Question&Answers more detail:
os