Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 693
Jikku Jose Avatar asked Aug 04 '13 14:08

Jikku Jose


2 Answers

Use list.pop:

>>> a = [1,2,3,4]
>>> a.pop(2)
3
>>> a
[1, 2, 4]

According to the documentation:

s.pop([i])

same as x = s[i]; del s[i]; return x

UPDATE

For chaining, you can use following trick. (using temporary sequence that contains the original list):

>>> a = [1,2,3,4]
>>> [a.pop(2), a][1] # Remove the 3rd element of a and 'return' a
[1, 2, 4]
>>> a # Notice that a is changed
[1, 2, 4]
like image 110
falsetru Avatar answered Oct 24 '22 00:10

falsetru


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]
like image 25
LondonRob Avatar answered Oct 23 '22 23:10

LondonRob