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)
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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With