Python and Ruby all have the insert method.
Python:
>>> a=[1,2,3,4,5]
>>> a.insert(0, 0)
>>> a
[0, 1, 2, 3, 4, 5]
Ruby:
a=[1,2,3,4,5]
# => [1, 2, 3, 4, 5]
a.insert(0,0)
# => [0, 1, 2, 3, 4, 5]
They have the same effect, but if give negative index, the result is different.
Python:
>>> a=[1,2,3,4,5]
>>> a.insert(-1, 6)
>>> a
[1, 2, 3, 4, 6, 5]
Ruby:
a=[1,2,3,4,5]
# => [1, 2, 3, 4, 5]
a.insert(-1, 6)
# => [1, 2, 3, 4, 5, 6]
Why there is this differences? How to understand?
in the python : insert(x, val), it means insert to the location before x.
so, a.insert(-1, 6)-> put the 6 before -1(location)
in the ruby : it means insert to this location x.
so, a.insert(-1, 6)-> put the 6 at -1.
In Python, the new object is inserted before the element of that certain index. Given an insertion point of 0, a new element is inserted before the item at index 0, which results in the inserted item becoming first. Given an insertion point of -1, a new element is inserted before the last item, so it becomes the second-to-last element.
If you want to insert something to the end of a Python list, simply use append().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With