nmmdl - 3 years ago 74

Python Question

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)`

`a.append(x)`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

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 [396]: x = [1, 2, 3]
In [397]: x[-1]
Out[397]: 3
In [398]: x[len(x) - 1]
Out[398]: 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 [400]: x.insert(-1, 4); x
Out[400]: [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.