How to slice middle element from list

To remove an item in-place call:

your_list.pop(index)

It will return the removed item and change your_list.


You cannot emulate pop with a single slice, since a slice only gives you a single start and end index.

You can, however, use two slices:

>>> a = [3, 4, 54, 8, 96, 2]
>>> a[:2] + a[3:]
[3, 4, 8, 96, 2]

You could wrap this into a function:

>>> def cutout(seq, idx):
        """
        Remove element at `idx` from `seq`.
        TODO: error checks.
        """
        return seq[:idx] + seq[idx + 1:]

>>> cutout([3, 4, 54, 8, 96, 2], 2)
[3, 4, 8, 96, 2]

However, pop will be faster. The list pop function is defined in listobject.c.

Tags:

Python

Slice