 nmmdl - 3 years ago 74
Python Question

# Why doesn't a.insert(-1, x) mimic a.append(x)?

So I have the following Python code, which appends numbers 1-10 to the list

`values`
:

``````values = []

for value in range(1, 11):
values.append(value)

print(values)
``````

And, as expected, gives us
`[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`
.

Although impractical, just out of curiosity, I attempted to recreate this result using
`insert()`
`append()`
:

``````values = []

for value in range(1, 11):
values.insert(-1, value)

print(values)
``````

Which gave me the result
`[2, 3, 4, 5, 6, 7, 8, 9, 10, 1]`
.

I tried this with other ranges as well, and the same thing happens every time: It is in ascending order, except for the smallest number being at the end.

From the Python Documentation Tutorial, I now know that
`a.insert(len(a), x)`
can be used to mimic
`a.append(x)`
. However, I still do not understand why inserting the values to the last position in a list works except for the smallest value. cᴏʟᴅsᴘᴇᴇᴅ

The fundamental thing to understand is that `-1` is not the same as `len(a)`. It is indeed the same as `len(a) - 1`:

``````In : x = [1, 2, 3]

In : x[-1]
Out: 3

In : x[len(x) - 1]
Out: 3
``````

When the list has size 1 and more, then `len(a) - 1` will always point to the spot just before the last element (or, technically, to the spot at which the last element currently is), which is where `list.insert` will put your new item.

``````In : x.insert(-1, 4); x
Out: [1, 2, 4, 3]
``````

As you've already figured out, `len(a)` points to the spot just after the last element, which is where `list.append` inserts elements. So, `-1`, or `len(a) - 1` will point to the spot of the last element, and `list.insert(-1, ...)` will push the last element to the right, and place the new element in the last element's old position.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download