Search code examples
pythonlistswap

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


I am new to Python and with the swapping exercise, I cannot swap the first and last element of the list using the following code (the line with issue noted below).

def swapList(list):
     
    first = list.pop(0)  
    last = list.pop(-1)
     
    list.insert(0, last) 
    list.insert(-1, first)  # this line is the issue.
    # It does not swap first to the last position in the list,
    # but instead place it just before the last number. If I change
    # it to list.append(first) then the issue is solved.
    # I cannot understand why.
     
    return list

Can you please help?


Solution

  • 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]