Home > database >  python index [-1] shows wrong element
python index [-1] shows wrong element

Time:01-29

As I learned, in python index -1 is the last number. for instant in:

values = [1, 2 , 3, 4, 5, 6, 7, 8, 9, 10]

print(value[-1]) 

returns 10 in output.

Now, if I want to insert a number in the last position with insert method, I do:

value.insert(-1,11)

and I expect to have:

[1, 2,3, 4, 5, 6, 7, 8, 9, 10, 11]

but, this is what I get in output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 10]

CodePudding user response:

list.insert(i, x)

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).


The 11 is inserted just before the last element (index -1), which is 10.

CodePudding user response:

The parameter "index" you give to the insert function (e.g. -1) is the index the element you want to insert will be but only relative to the original list. So the -1th element is the 10th element in your original list (with index 9) and so the inserted element will have that index (9). If you want to insert the element at the end, you need to use: values.insert(len(values),11) or values.append(11)

Append adds the element at the end, the first one inserts 11 as index 10 and therefor as 11th element.

CodePudding user response:

When you use an .insert() function you insert an element into the list, and all subsequent ones are shifted. So in your code you inserted 11 to the -1 position and 10 moved. If you want 11 to be in the -1 position, just use .append() function because it adds the element to the last position, or use values.insert(len(values), 11). It will add 11 to the position after 10 meaning that 11 will be last.

  • Related