How to remove the first and last elements of a list and return the list without those elements?

I have a function middle(c) that accepts as input a list c and outputs the list c and the problem that I need to solve is outputting this list without the first and last elements. My code is below.

    def middle(c):
     del c[0]
     del c[-1]
     return middle(c)

It gives me this after running the code Exception “list assignment index out of range” I had some similar problems where I returned c[0] to find the first element of the list which worked so maybe the problem is with the return statement?


The simplest way is to pull everything from index 1 to -1.

def middle(c):
    return c[1:-1]


Originally in my answer I incorrectly stated that c[1::-1] would result in an IndexError if c had a length of 0 or 1. This is because slicing a list does not actually pull each element at each index, as I expected.

Slicing can be more appropriately described as checking to see if an index exists and then pulling the value for the resulting slice. So in the expression [][1::] python attempts to take a slice of every element from the list but the first. When no element is found that satisfies that, none is added to the resultant list and no IndexError` is thrown.