Issues with list index after swapping first and last number in the list

The Python documentation says this about list.insert:

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

So this is what happens to the list:

>>> xs = [1, 2, 3, 4, 5]
>>> first = xs.pop()
>>> 
>>> xs = [1, 2, 3, 4, 5]
>>> first = xs.pop(0)
>>> last = xs.pop(-1)
>>> 
>>> xs
[2, 3, 4]
>>> 
>>> xs.insert(0, first)
>>> xs
[1, 2, 3, 4]
>>> xs.insert(-1, last)
>>> xs
[1, 2, 3, 5, 4]
>>> 

The index you specify is “the index of the element before which to insert”, so insert(-1, 5) inserts 5 before the last element. So if you change the line to list.insert(len(list), last), your function will work as expected


However, there’s a better way to do this. If you want to swap the first and the last item in the list, you can use tuple unpacking:

xs[0], xs[-1] = xs[-1], xs[0]

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top