0

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]
2
  • 1
    value -> values
    – Joshua Fox
    Jan 29 at 8:45
  • when using insert it will insert it before the last element use append instead
    – Ali Redha
    Jan 29 at 8:46

3 Answers 3

3

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.

0

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.

0

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.