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

I just noticed that in Python there is no function to delete an item in a list by index, which will be used when chaining.

For example, I am looking for something like this:

another_list = list_of_items.remove[item-index]

instead

del list_of_items[item_index]

Since remove(item_in_list) returns a list after removing item_in_list ; I wonder why there is no similar function for the index. It seems very obvious and trivial to be included, believes that there is reason to skip this.

Any thoughts on why such a feature is not available?

----- EDIT -------

list_of_items.pop(item_at_index) not suitable because it does not return a list without deleting a specific item, so it cannot be used for chaining. (According to the Docs: L.pop ([index]) β†’ item - delete and return the item by index)

+4
source share
3 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 the chain, you can use the following trick. (using the time sequence containing the source 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] 
+1
source

As Martijn Pieters noted in the comments on the question, this is not implemented as: Python in-place operations typically return None, an object never modified.

0
source

Here's a good Pythonic way to do this with a list of concepts and enumerate (note that enumerate has zero indexing):

 >>> 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 actions 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] 
0
source

Source: https://habr.com/ru/post/1495201/


All Articles