5
votes

-1 is not inserting the "hello" at the last index of the array

If I have an array, x:

>>> x = [1, 2, 3] then
>>> x.insert(-1, "hello")
>>> print(x)
[1, 2, 'hello', 3]

Why -1 is not inserting the "hello" at the last index of the array? As -1 index is refered to the last item of the list, so I was expecting:

[1, 2, 3, "hello"]

5
@glibdud: I was not asking "how to insert at the last?" My question was why index with -1 didn't insert the item at the last?(as -1 always refers to the last index of the list) - nileshkumar
x.insert(-1, "hello") this won't work because -1 is not an index of an array. If you want to access the last index of the array then you have to specify the array inside the insert() like this... a.insert(a[-1], 'hello') - Farhan

5 Answers

3
votes

.append(item) is to append to the end.

.insert(index, item) inserts to the place before another item. To "insert" to end, use .insert(len(x), item).

Read more at Python documentation.

5
votes

Running help on method will usually give you the answer for these kind of questions:

help(list.insert)
#Help on method_descriptor:
#
#insert(self, index, object, /)
#    Insert object before index.
3
votes

If you want to add an element in the last using insert() function, then you have to specify the total length as index. You cannot use negative indexes. Negative indexes will start inserting from second last position and before.

x = [1, 2, 3]
x.insert(len(x),'hello')
x
   [1, 2, 3, 'hello']
2
votes

From the google's documentation: https://developers.google.com/edu/python/lists

list.insert(index, elem) -- inserts the element at the given index, shifting elements to the right.

Insert should be read as: "insert elem before the index" in your case: "insert 'hello' before the -1'th element (last element of the list) which is 3".

To insert to the end of the lists you should use list.append(elem) instead.

list.append(elem) -- adds a single element to the end of the list.

0
votes

So you want to add value at the end of the list. There is two way to add.

- Append: As the name says it will append (add) value to the last of the list

>>> x = [1,2,3,4]
>>> x.append('hello')
>>> x 
[1, 2, 3, 4, 'hello']

- Insert: Now in Insert you have to give the position where you want to add the value. so when you write

>>> x.insert(len(x),5)
>>> x
[1, 2, 3, 4, 'hello', 5]

You are defining as to put value 5 at position len(x) ie 5