Skip to content Skip to sidebar Skip to footer

Array: Insert With Negative Index

-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

Solution 1:

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.

Solution 2:

.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.


Solution 3:

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']

Solution 4:

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.


Solution 5:

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


Post a Comment for "Array: Insert With Negative Index"