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.

6th Nov 2016, 10:02 PM
Geoff Colman
Geoff Colman - avatar
4 odpowiedzi
+ 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
15th Nov 2016, 10:28 PM
Isai Cortes
Isai Cortes - avatar
0
Okay, that wasn't immediately clear from their examples. Thanks!
15th Nov 2016, 10:31 PM
Geoff Colman
Geoff Colman - avatar
- 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.
7th Nov 2016, 6:22 AM
Richard Carrigan
Richard Carrigan - avatar
- 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.
11th Nov 2016, 5:30 AM
Geoff Colman
Geoff Colman - avatar