0
What's the point of "arr.insert(index, value)", when "arr[index] = value" does the same thing?
I don't see any immediate advantage to the method call over the direct assignment literal - particularly when it's actually more verbose, and not appreciably more readable. The only possible explanation I can see is for the sake of accessing private data in other people's implementations, but this doesn't seem sufficient.
4 Answers
+ 8
If you have
arr = [1,2,3,4]
Using arr.insert(2,5) will insert a new element in the list and the result will be arr = [1,2,5,3,4]
And arr[2]=5 will replace the value in the position 2 which will result as arr = [1,2,5,4]
I hope that it helps
0
Okay, that wasn't immediately clear from their examples. Thanks!
- 1
I don't think one is better than the other, logically, but it makes it more convenient for the programmer to achieve the same result using whichever method is more intuitive to them.
- 1
Since the method call is an idiom without a clear, objective advantage in terms of verbosity; readability; expressivity; or performance, I'm trying to wrap my head around why it would have been implemented in the first place.