Home > Net >  Interchange First and Last Elements in a list in Python
Interchange First and Last Elements in a list in Python

Time:01-17

def changeList(k):
    first = k.pop(0)
    last = k.pop(-1)
    k.insert(0, last)
    k.insert(-1, first)
    return k

k = [9, 0, 4, 5, 6]
print(changeList(k))

My goal is to interchange the first and last elements in my list. But when I run the code, it switches to this list [6, 0, 4, 9, 5], instead of [6, 0, 4, 5, 9].

I tried popping the first and last elements in my list, and then tried inserting the new elements in my list.

CodePudding user response:

The way list.insert(index, element) works is that it will put that element in that specific index. Your list right before the last insert is [6, 0, 4, 5]. Index -1 refers to the last index at the time prior to the index being inserted, which is index 3. So it puts 9 at index 3, resulting in [6, 0, 4, 9, 5].

You can use the swaps as shown in earlier answers, or you can use list.append() to add to the very end.

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

in your code you can change k.insert(-1, first) to k.insert(len(k), first) Let's go through some example:

>>> a = [1,2,3,4,5]
>>> a.insert(0, 10)    # insert happens to position left and all elements after that moved one position right.
>>> a
[10, 1, 2, 3, 4, 5]
>>> a.insert(1, 20)
>>> a
[10, 20, 1, 2, 3, 4, 5]
>>> a.insert(-1, 30)   # here -1 means last element so insert will happen left of last element
>>> a
[10, 20, 1, 2, 3, 4, 30, 5] # as expected.
>>> a.insert(len(a), 40)   # use len(list) to insert at the last of list.
>>> a
[10, 20, 1, 2, 3, 4, 30, 5, 40]
  • Related