In-place function to remove an item using index in Python

chaining, list, python

Solution

Here's a nice Pythonic way to do it using list comprehensions and `enumerate` (note that `enumerate` is zero-indexed):

>>> y = [3,4,5,6]
>>> [x for i, x in enumerate(y) if i != 1] # remove the second element
[3, 5, 6]

The advantage of this approach is that you can do several things at once:

>>> # remove the first and second elements
>>> [x for i, x in enumerate(y) if i != 0 and i != 1]
[5, 6]
>>> # remove the first element and all instances of 6
>>> [x for i, x in enumerate(y) if i != 0 and x != 6]
[4, 5]

Problem

Just noticed that there is no function in Python to remove an item in a list by index, to be used while chaining. For instance, I am looking for something like this: `another_list = list_of_items.remove[item-index]` instead of `del list_of_items[item_index]` Since, `remove(item_in_list)` returns the list after removing the `item_in_list`; I wonder why a similar function for index is left out. It seems very obvious and trivial to have been included, feels there is a reason to skip it. Any thoughts on why such a function is unavailable? ----- EDIT ------- `list_of_items.pop(item_at_index)` is not suitable as it doesn't return the list without the specific item to remove, hence can't be used to chain. (As per the Docs: L.pop([index]) -> item -- remove and return item at index)

Original source

Related problems